I'm writing the file like this:
Dim objWriter As New System.IO.StreamWriter("C:\Users\Administrador\Documents\div.dat")
objWriter.Write(data)
objWriter.Close()
And reading it like this
Dim line As String = IO.File.ReadAllText("C:\Users\Administrador\Documents\div.dat")
However line is simply empty, no error is returned, the file does exist, and I can open it with notepad and it has plain text inside.
Related
I want to get The Subfolder Name Listed in my Textfile.
I don't want to see the path for the SubFolder.
I finally got a way to show only to my VS Console. But If i try to save it to my txt file it keeps on writing only the first line even though I used For. Please Help Me!
Here's the code that writes to the console
Dim di As New IO.DirectoryInfo(startPath)
Dim Drs() As IO.DirectoryInfo = di.GetDirectories()
For Each dr As IO.DirectoryInfo In Drs
Console.WriteLine(dr.Name)
Next
This is the code that I tried to Write It on a txt file. It only writes 1 Line
For Each Dir As String In Directory.GetDirectories(startPath)
My.Computer.FileSystem.WriteAllText("C:\Test.txt", Dir, False)
Next
The Expected Output is
SubFolder1
SubFolder2
SubFolder3
SubFolder4
SubFolder5
Like this in txt file
You are using the wrong method, WriteAllText always overwrites the complete file, you want to append a new line. You could use File.AppendAllText:
For Each Dir As String In Directory.GetDirectories(startPath)
System.IO.File.AppendAllText("C:\Test.txt", Dir)
Next
Another option, use a StreamWriter, it has a constructor that takes a Boolean to append text:
Using writer As New System.IO.StreamWriter(startPath, True)
For Each Dir As String In Directory.GetDirectories(startPath)
writer.WriteLine(Dir)
Next
End Using
i'm getting a error 75 - file/path access error when i attempt to delete my file (last lines of the code block below):
' make a reference to a directory
Dim directory As New IO.DirectoryInfo(WatchDirectory) 'ex C:\Print\Realtime\
Dim directoryList As IO.FileInfo() = directory.GetFiles(WatchFilter) 'ex *.xml
Dim directoryFile As IO.FileInfo
'list the names of all files in the specified directory
For Each directoryFile In directoryList
'scans the Realtime folder (WatchDirectory) for each specified file (WatchFilter / xml) for processing.
If directoryFile.Name = RealTimeFile Then
'checks if the file is realtime by matching the name up to the ProcessRealtimeFile app setting (ex realtime.xml)
Continue For
Else
'this is not a ProcessRealtimeFile app setting (ex realtime.xml) file
Dim Name As String
Dim renameRetries As Integer = 5
'get file name without extension
Name = IO.Path.GetFileNameWithoutExtension(directoryFile.Name)
While True
Try
If File.Exists(ProcessDirectory & RealTimeFile) = False Then
'the current file to be checked against in the watch directory does not exist in the processdirectory (ex. C:\Print\Oracle\xml.rt\). continue.
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "File " & directoryFile.FullName & " is being processed by scrape.")
If ArchiveXML = True Then
'copy the current file to the archive directory (ex C:\print\xml.rt\archive\), overwriting the existing file if exists
System.IO.File.Copy(directoryFile.FullName, ArchiveDirectory & directoryFile.Name, True)
End If
'update the date and time of the active file to now
System.IO.File.SetLastWriteTime(directoryFile.FullName, Date.Now)
Log.Write(Log.Level.Information, "RTPrint-Diamond", Environment.UserName, Environment.MachineName, "Date Changed.")
If ISPublisher(directoryFile.FullName) Then
'Current file is a publisher file. Process
Dim fileInfo As New IO.FileInfo(directoryFile.FullName)
Dim utf8WithoutBOM As New System.Text.UTF8Encoding(False) 'file encoding type - UTF8 w/o BOM
Using writer As StreamWriter = New StreamWriter(Path.Combine(PublisherProcessDirectory, directoryFile.Name), False, utf8WithoutBOM)
'set up write to the publisher process directory (ex C:\print5x\xml.rt\)
'publisher requires utf8 w/o BOM to read the file. We need to change the encoding type to this standard.
'this converts the file to utf8 w/o BOM to the 5x output destination
Using reader As StreamReader = fileInfo.OpenText
While Not reader.EndOfStream
Dim line As String = reader.ReadLine
writer.Write(line & vbCrLf)
End While
reader.Close()
End Using
writer.Close()
End Using
If File.Exists(Path.Combine(PublisherProcessDirectory, directoryFile.Name)) Then
'make sure the destination file was successfully re-written in utf8 w/o bom and delete the source file
If IsFileOpen(directoryFile.FullName, 1) = True Then
Microsoft.VisualBasic.FileClose(1)
End If
System.IO.File.Delete(directoryFile.FullName)
End If
I even tested with some sample solutions I read on this site to run a function test to see if the lock is present (giving error 75), and if true is returned, attempt a file close which also is not doing anything.
Obviously my writer.Close() is not doing the job. Can anyone spot why the System.IO.File.Delete(directoryFile.FullName) is not allowing me access to this text file for deletion, and how i can unlock it to delete? Is it the for each that is locking my file? I need to delete the file within the loop, so if the for loop is locking me, what are the work-arounds here?
Additionally, i tested the delete by removing the entire writer block and 2 declared variables above it, and the file still had a lock. This can help to isolate the issue to the surrounding logic and not the streamWriter portion.
Thanks in advance!
I am working on file writing in Vb.net. I know how to override a specific line in a text file but when it is empty or equal to "" , it fails.
I tried with
Dim lines() As String = System.IO.File.ReadAllLines("filepath")
lines(4) = "to replace text"
System.IO.File.WriteAllLines(filepath, lines)
It shows a Index out of array exception. It might be because the line in the file is empty.
Thank you
I am making a class that is to help with saving some strings to a local text file (I want to append them to that file and not overwrite so that it is a log file). When I write with the streamwriter to find the end of the previous text, I get an error "the file is not available as it is being used by another process". I looked into this problem on MSDN and I got very little help. I tried to eliminate some variables so I removed the streamreader to check was that the problem and it was. When I tried to write to the file then it worked and I got no error so this made me come to the conclusion that the problem arose in the streamreader. But I could not figure out why?
Here is the code:
Public Sub SaveFile(ByVal Task As String, ByVal Difficulty As Integer, ByVal Time_Taken As String)
Dim SW As String = "C:/Program Files/Business Elements/Dashboard System Files/UserWorkEthic.txt"
Dim i As Integer
Dim aryText(3) As String
aryText(0) = Task
aryText(1) = Difficulty
aryText(2) = Time_Taken
Dim objWriter As System.IO.StreamWriter = New System.IO.StreamWriter(SW, True)
Dim reader As System.IO.StreamReader = New System.IO.StreamReader(SW, True)
reader.ReadToEnd()
reader.EndOfStream.ToString()
For i = 0 To 3
objWriter.WriteLine(aryText(reader.EndOfStream + i))
Next
reader.Close()
objWriter.Close()
End Sub
As Joel has commented on the previous answer it is possible to change the type of locking.
Otherwise building on what Neil has suggested, if to try to write to a file with a new reader it is difficult not to lose the information already within the file.
I would suggest you rename the original file to a temporary name, "UserWorkEthicTEMP.txt" for example. Create a new text file with the original name. Now; read a line, write a line, between the two files, before adding your new data onto the end. Finally Delete the temporary file and you will have the new file with the new details. If you have an error the temporary file will serve as a backup of the original. Some sample code below:
Change file names
Dim Line as string
line=Reader.readline
Do until Line=nothing
objwriter.writeline(line)
line=reader.readline
loop
add new values on the end and remove old file
You are trying to read and write to the same file and this is causing a lock contention. Either store the contents of the file into a variable and then write it back out including your new data to the file.
Psuedo
Reader.Open file
String content = Reader.ReadToEnd()
Reader.Close
Writer.Open file
Loop
Writer.Write newContent
Writer.Close
I'm trying to check to see if a file exists, if so it does nothing. If the file does not exist is creates the text file. Then I want to write text to that file. Where am I going wrong with this code? I'm just trying to write multiple lines to the text file and that part is not working. It is creating the text file... just not writing to it.
Dim file As System.IO.FileStream
Try
' Indicate whether the text file exists
If My.Computer.FileSystem.FileExists("c:\directory\textfile.txt") Then
Return
End If
' Try to create the text file with all the info in it
file = System.IO.File.Create("c:\directory\textfile.txt")
Dim addInfo As New System.IO.StreamWriter("c:\directory\textfile.txt")
addInfo.WriteLine("first line of text")
addInfo.WriteLine("") ' blank line of text
addInfo.WriteLine("3rd line of some text")
addInfo.WriteLine("4th line of some text")
addInfo.WriteLine("5th line of some text")
addInfo.close()
End Try
You don't seem to be properly releasing the resources you allocated with this file.
Make sure that you always wrap IDisposable resources in Using statements to ensure that all resources are properly released as soon as you have finished working with them:
' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
Return
End If
Using Dim addInfo = File.CreateText("c:\directory\textfile.txt")
addInfo.WriteLine("first line of text")
addInfo.WriteLine("") ' blank line of text
addInfo.WriteLine("3rd line of some text")
addInfo.WriteLine("4th line of some text")
addInfo.WriteLine("5th line of some text")
End Using
but in your case using the File.WriteAllLines method seems more appropriate:
' Indicate whether the text file exists
If System.IO.File.exists("c:\directory\textfile.txt") Then
Return
End If
Dim data As String() = {"first line of text", "", "3rd line of some text", "4th line of some text", "5th line of some text"}
File.WriteAllLines("c:\directory\textfile.txt", data)
It all works great! - This is not the best way to create and write to a file - I'd rather create the text I want to write and then just write it to a new file, but given your code, all that is missing is having to close the created file before writing to it.
Just change this line:
file = System.IO.File.Create("c:\directory\textfile.txt")
to:
file = System.IO.File.Create("c:\directory\textfile.txt")
file.close
All the rest will work.
file = System.IO.File.Create("path")
Close the file once created then try to write to it.
file.Close()
Dim addInfo As New System.IO.StreamWriter("path")