Read and Write to specific line in textfile with VB.Net 2 - vb.net

I have tried using the solution (given below) for the "Read and Write to specific line in textfile with VB.Net" problem asked 4 years ago
Dim filePath As String = "E:\myFile.txt"
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
If lines.Length > 4 AndAlso lines(4).StartsWith("ORIGIN ") Then
lines(4) = "ORIGIN ""250"""
System.IO.File.WriteAllLines(filePath, lines)
End If
But each time I encounter the following error:
The process cannot access the file 'file_path' because it is being
used by another process.
Any idea as to why this happens?

Your code works OK for me. System.IO.File.ReadAllLines() is supposed to close the file afterwards.
Maybe something else is preventing write access to the file. (Some application you're using to see if it's working?!) To check that, replace
Dim lines() As String = System.IO.File.ReadAllLines(filePath)
with
Dim lines() As String = {"0","1","2","3","ORIGIN 4", "5"}
and see if it still fails.

Related

vb check for specific file type in dir and perform code

I'm trying to make a program that checks for specific file type in a directory, then executes a code if there are any files of that type found.
I'm assuming something like this:
For Each foundFile As String In
My.Computer.FileSystem.GetFiles(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
(If any found files are, for example, "txt" files, then display their content.)
Next
Thanks in advance.
You can use Directory.GetFiles or Directory.EnumerateFiles with a parameter for the extension-filter:
Dim directoryPath = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim allTxtFiles = Directory.EnumerateFiles(directoryPath, ".txt")
For each file As String In allTxtFiles
Console.WriteLine(file)
Next
The difference between both methods is that the first returns a String(), so loads all into memory immediately whereas the second returns a "query". If you want to use LINQ it's better to use EnumerateFiles, f.e. if you want to take the first 10 files:
Dim firstTenFiles As List(Of String) = allTxtFiles.Take(10).ToList()
Dim di As DirectoryInfo = New DirectoryInfo(My.Computer.FileSystem.SpecialDirectories.MyDocuments)
For Each fi In di.GetFiles("*.txt")
Dim content As String = My.Computer.FileSystem.ReadAllText(fi.FullName)
Console.WriteLine(fi.Name)
Next

vb.net How to save File as Word & Open Office Document?

I have a small programm and i want to save the File so i can read them later into when i open it.
How can i now save the File cause i must save 5 Variables and read them back into the Tool and if its possible i want to use the File in Word or OpenOffice too.
My Variables
Title - Pieces- SinglePrice- Totalprice
Please give me Examples for the Point in the right way.
Thanks everyone!
If all you want to do is store four variables from your program in a file that can also be read by Word and OpenOffice, you can do that easily enough with a text file. The following code assumes that Title is a String, Pieces is an Integer, SinglePrice and TotalPrice are Decimal.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = {Title, Pieces.ToString, SinglePrice.ToString, TotalPrice.ToString}
System.IO.File.WriteAllLines(saveFile, vars)
If you need to read the file to restore the values of the variables, you can do it like this. Note that this code assumes that the file was written by the first snippet of code, otherwise it would be necessary to validate the contaents of the file before using it.
Dim folder As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim saveFile As String = System.IO.Path.Combine(folder, "Save.txt")
Dim vars() As String = System.IO.File.ReadAllLines(saveFile)
Title = vars(0)
Pieces = CInt(vars(1))
SinglePrice = CDec(vars(2))
TotalPrice = CDec(vars(3))

Visual Basic Append to a specific point in a text file

I am currently trying to manipulate a line in a file that we are using to retain data, using comma delimiters. For example -
121,1212, XJAY,Sean K,Kean S,AAAA-BBBB-AAAA-BBBB-AAAA
12456,987654,WYST,Steve Jobs,Bill Gates,CAAA-BBBB-AAAA-BBBB-AAAA
If I assume that the last line is always a unique code, is it possible to identify that line in the text file and append it with another field?
Prior research has been reading through the APIs for StreamReader and StreamWriter, and looking through other StackOverflow questions, however most questions seem focused on just appending to the end of the file, or in different languages!
As always thank you for your time, and if there is anything I've left off please let me know!
You can't manipulate a line in a file in any reasonably easy way.
There are no methods to work with lines in a file, because files are not line based. They are not even character based. The bytes in the file are decoded into characters, then the line break characters are recognised and the characters can be split into lines.
The easiest way to manipulate a line is to read the entire file into a string array, change the string that you want change, then write the entire string array to the file.
Example:
Dim fileName As String = "c:\data.txt"
Dim lines As String() = File.ReadAllLines(fileName)
For i As Integer = 0 To lines.Length - 1
Dim line As String = lines(i)
If line.StartsWith("12456,") Then
lines(i) = line & ",More data"
End If
Next
File.WriteAllLines(fileName, lines)
If you are looking for a way to parse Each line with StreamReader and StreamWriter: Here it is:
'You will need Imports System.IO
Dim TheNewFile As String
Dim MyLine As String
Dim MyStream2 As New FileStream("C:\Your Directory\YourFile.txt", FileMode.Open)
Dim MyReader As New StreamReader(MyStream2)
Dim MySettings As New StringReader(MyReader.ReadToEnd)
MyReader.BaseStream.Seek(0, SeekOrigin.Begin)
MyReader.Close()
MyStream2.Close()
Try
Do
MyLine = MySettings.ReadLine
'This if statement is an exit parameter. It can be if it contains or if 5 consecutive lines are nothing. It could be a number of things
If MyLine Is Nothing Then Exit Do
'This is the file you will write. You could do if MyLine = "Test" Then ........... append whatever and however you need to
TheNewFile = TheNewFile & MyLine & vbCrLf
Loop
Catch ex As Exception
MsgBox(ex.ToString())
End Try
'-----------------Write The new file!!!----------------
Dim MyStream3 As New FileStream("C:\Where you want to write New File\NewFileName.txt", FileMode.Create)
Dim MyWriter3 As New StreamWriter(MyStream3)
MyWriter3.Write(TheNewFile & "Test")
MyWriter3.Close()
MyStream3.Close()

StreamReader not finding end of file

I simply need to read lines from a text file and show them. When I run this I can see that id does what I want, but after it reads the last value it just shows a blank form on my screen and does not move on. It seems like it can't find the end of the file or something. I don't get an error.
Using sr As New System.IO.StreamReader(Application.StartupPath & "\myfile.cfg")
Dim Line As String = ""
Dim i As Integer = 0
Dim temp_array As Array
Do While Line IsNot Nothing
Line = sr.ReadLine
temp_array = Line.Split("=")
'MessageBox.Show(temp_array(0))
Loop
End Using
That is bad code because you're actually going to use Line before testing whether it's Nothing. Here are two good options for looping through the lines of a text file:
Using reader As New StreamReader(filePath)
Dim line As String
Do Until reader.EndOfStream
line = reader.ReadLine()
'...
Loop
End Using
For Each line In File.ReadLines(filePath)
'...
Next
As you can see, the second is far more concise but it does require .NET 4.0 or later.

Vb string replacement

Dim sr as new IO.streamreader(xxx.txt)
Dim sw as new IO.streamwriter(xxxx.txt)
Dim s as string = sr.readtoend
dim ssss as string
dim i as integer
while not sr.endofstream
for i = 0 to 10
ssss = "hello" & listbox.items(i)
s = replace(s,"[[abc]]",ssss)
Call sw.writeline(s)
Next
End while
call sw.close()
I was trying to replace the string [[abc]] in a .txt file called xxx with ssss and then write it into another .txt named xxxx. The problem is that ssss is changing all the time and when I debug the program it says s is "Nothing". I need all ssss values in the new txt. So I wonder maybe "Replace" is not suitable in this case? Any ideas on how to fix this issue? BTW, I am using vb in vs 2012, not vb 6.0. Thanks.
It seems you are having errors with null. Try to catch whenever "s" is nothing, then if it is, skip it. Otherwise do the Replace.
Check it with something like
if s <> nothing then
s = s.replace(s,"[[abc]]",ssss)
Call sw.writeline(s)
next