text file im trying to overwrite is being used by another process, but it is not in use? - vb.net

im trying to overwrite a text file saved on an external drive using an openfile dialog in vb.net winforms, and i keep getting the error:
System.IO.IOException: 'The process cannot access the file 'F:\SETTINGS.TXT' because it is being used by another process.' after clicking the save button, i get the error.
here is my code:
` Public Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim myStream As Stream
Dim FileSaveLocation As String
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
If openFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = openFileDialog1.OpenFile()
FileSaveLocation = openFileDialog1.FileName
MessageBox.Show(FileSaveLocation)
If (myStream IsNot Nothing) Then
Dim file As System.IO.StreamWriter
IO.File.WriteAllText(FileSaveLocation, "SETTINGS.txt")
file.WriteLine("list of variables and text go here, hidden for privacy" ,True)
File.Close()
End If
End If
End Sub`
ive been switching around the code and slowly making my way through different issues and errors, i thought maybe it has a strange error with the messagebox but removing that makes no difference, but im really stumped on this one, can anyone help? thanks a tonne in advance, its hurting my brain XD

You're opening the file...
myStream = openFileDialog1.OpenFile()
... and then calling WriteAllText which tries to open the file as well...
IO.File.WriteAllText(FileSaveLocation, "SETTINGS.txt")
If you truly do need to open the file to evaluate some condition before you write then you'll need to be sure to close myStream before the call to WriteAllText

Related

How to WriteAllText but restrict to overwrite the existing file?

Jan 8. 2023:
The AppendAllText can append into existing file and can create a file if no file exist.
the WriteAllText can Write into new created file and overwrite the existing file.
I'm trying to find another alltext for what I want to happen.
What I want to do is to save my textboxcontent.text into txt file.
I want to save 3 different content that will be displayed into my textboxcontent.text
And I only have one button.
That one button will open savefiledialog but with the code I have, I can only do 2 things, Write and Append.
Now, This is what suppose to happen.
*If I save the textcontent.text to an existing txt file, it will prompt message box "Do you want to overwrite this file?" And even if I click Yes, it will not allow to.
I must be able to create new txt file since I was not able to overwrite the file.
The reason is because I don't want to delete or overwrite the existing file with important information saved in it.
I hope somebody can help me.
This is the code I have.
```Imports System.io
Private lastSaveFileName As String = String.Empty
Private Function GetSaveFileName3(ByVal suggestedName As String) As String
Using sfd3 As New SaveFileDialog()
sfd3.Filter = "Text Files (*.txt) |*.txt"
sfd3.FileName = suggestedName
sfd3.OverwritePrompt = True
If DialogResult.OK Then
End If
If sfd3.ShowDialog() = DialogResult.OK Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
Else
End If
Return String.Empty
End Using
End Function
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
lastSaveFileName = GetSaveFileName3(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.AppendAllText(lastSaveFileName, TextContent.Text)
End If
End Sub ' This code above includes IMPORTS.IO
Jan 9, 2023: Update
This is what I've done so far.
I tried to use the File.Exist but I don't know where to place it to make it run in the way I wanted.
Please see this code and help me fix it.
This code is running well in almost the way I want. I'm missing something.
Imports System.IO
Private lastSaveFileName As String = String.Empty
Private Sub SaveFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveFile.Click
If Not File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
ElseIf File.Exists(lastSaveFileName) Then
lastSaveFileName = GetSaveFileName2(lastSaveFileName)
If Not String.IsNullOrEmpty(lastSaveFileName) Then
File.WriteAllText(lastSaveFileName, txtdisplay1.Text)
End If
End If
End Sub
Private Function GetSaveFileName2(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
'If File.Exists(lastSaveFileName) Then
MessageBox.Show(
Me, "Your activity is not saved! This file have records from your last session, you cannot overwrite this file. Please create new file to save new records.",
"Save error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation
)
End If
Return String.Empty
End Using
End Function
Private Function GetSaveFileName(ByVal suggestedName As String) As String
Using sfd As New SaveFileDialog()
sfd.Filter = "Text Files (*.txt) |*.txt"
sfd.FileName = suggestedName
sfd.OverwritePrompt = True
If sfd.ShowDialog() = DialogResult.OK Then
Return sfd.FileName
End If
Return String.Empty
End Using
End Function
With this code, I was able to save the textdisplay to a txtfile but it's like, it's bypassing the Elseif function.
Sometimes, poeple forgot to avoid important files and accidentally deleted it. This is what I'm preventing to happen.
I let the overwriteprompt true to let it ask the user if they want to replace. It accidentally click the yes, this will show message "This file have records from your last session, Please create new file to save new records." means that even the user want to replace it, the program will not allow it. I don't want to remove that scenario.
(Scenario 1)
What happen in this code is this, when I click the button, savefiledialog pop up and giving me choice how I want to save the textdisplay.
I can create new file or replace existing file.
First, I choose to replace, and a messagebox shows and saying, I can't replace the file.
Then I create new file, it lets me save the txt display normally.
(scenario 2)
That's what I want. The code runs that way at first, but if you click the button again, and try to create new file first, the message box will show saying I can't replace the file. then when I choose to replace, no message box shows and the file was replace. I lost the file.
That's where I need help. I only want the Scenario 1.
Please try on your own I you don't get what I mean.
I tried this and this code works the way I want.
Private Sub SaveButton_Click(sender As Object, e As EventArgs) Handles SaveButton.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
If File.Exists(saveFileDialog1.FileName) Then
MessageBox.Show("A file with that name already exists. Please select a different file name or choose a different location to save the file.")
Else
File.WriteAllText(saveFileDialog1.FileName, Txtdisplay1.Text)
End If
End If
End Sub
Answered by: schoemr

Using Savefiledialog to export Listbox

I'm using a savefiledialog to export a listbox into a .txt file or a .csv file. I've set the SFD under pressure of a button and it seems to work properly until I try to save the file, when I receive the following error:
Here is the code I'm using:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt|CSV Files (*.csv*)|*.csv"
If SaveFileDialog1.ShowDialog() = DialogResult.OK Then
Using writer = New StreamWriter(SaveFileDialog1.FileName)
For Each o As Object In Form3.ListBox1.Items
writer.WriteLine(o)
Next
End Using
End If
End Sub
How could I solve? Thanks all are gonna answer me. Best regards
I tried on my side, you need to delete the form3 before ListBox1.Items. I think that is why. I tried everything possible. Hope this helps.

Can open and read from file but not then resave to same file

I am using vb.NET and windows forms.
I have a simple form with a list box and two buttons.
btnLoadData opens up an OpenFileDialog and allows me to choose the text file to open, this is then read into the list box.
I can then delete items from the list box.
btnSaveList opens up a SaveFileDialog and allows me to choose a file to save to.
The problem occurs when I try to save to the same file that I read in.
It tells me that the file cannot be accessed as it is in use. It works if I choose a new file name.
I have searched and tried a number of different suggestions. I have altered the code a number of times and have finally decided I need to ask for help!
The code for the two buttons is below.
Private Sub btnLoadData_Click(sender As Object, e As EventArgs) Handles btnLoadData.Click
Dim openFD As New OpenFileDialog()
openFD.Filter = "Text [*.txt*]|*.txt|CSV [*.csv]|*.csv|All Files [*.*]|*.*"
openFD.ShowDialog()
openFD.OpenFile()
Dim objReader As New StreamReader(openFD.SafeFileName)
While objReader.Peek <> -1
lstList.Items.Add(objReader.ReadLine)
End While
objReader.Close()
End Sub
Private Sub btnSaveList_Click(sender As Object, e As EventArgs) Handles btnSaveList.Click
Dim saveFD As New SaveFileDialog()
If saveFD.ShowDialog = Windows.Forms.DialogResult.OK Then
Using objWriter As New StreamWriter(saveFD.FileName) 'Throws the exception here
For Each line In lstList.Items
objWriter.WriteLine(line)
Next
End Using
End If
End Sub
Private Sub lstList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstList.SelectedIndexChanged
lstList.Items.Remove(lstList.SelectedItem)
End Sub
Thank you.
You create two streams but only closing one at the end of reading the file. The OpenFile() method of the OpenFileDialog is creating a stream you doesn't close at the end so it stays open and locks the file. In your case you are using your own stream so you don't need the method OpenFile().
code for button #1 (read the file):
openFD.Filter = "Text [*.txt*]|*.txt|CSV [*.csv]|*.csv|All Files [*.*]|*.*"
openFD.ShowDialog()
'openFD.OpenFile()
Using objReader As New StreamReader(openFD.FileName)
While objReader.Peek <> -1
lstList.Items.Add(objReader.ReadLine)
End While
End Using
code for button #2 (write the file):
Dim saveFD As New SaveFileDialog()
If saveFD.ShowDialog = Windows.Forms.DialogResult.OK Then
Using objWriter As New StreamWriter(saveFD.FileName)
For Each line In lstList.Items
objWriter.WriteLine(line)
Next
End Using
End If
Opening a file for read will lock the file against writes and deletes; opening a file for write will lock against reads, writes and deletes.
You can override those locks but trying to both read and write a file at the same time creates its own set of problems.
There are two approaches to avoid this:
Read the whole file in and close before processing and writing. Of course the whole content has to be in memory.
Write to a temporary file, after closing the input and finishing writing delete the original file and rename the temporary file. This will not preserve attributes (eg. ownership, ACL) without extra steps.
However in your case I suspect you need to use a using block to ensure the file is closed after the read rather than depending on the GC to close it at some point in the future.

VB.NET 2010 Passing Picture from OpenFile Dialog Box to another form

I am creating a loan program that opens a Custom Form Dialog Box, you choose the picture, click open and then need to pass it to another form to use after hitting OK from the Dialog Box. This is my code when I click the Logo File button from my custom Dialog Form.
The Form is called Dialog Form and I need to send the picture to the NewLoanCaculatorForm to populate a picture area in the form.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogoFile.Click
Dim mystream As Stream = Nothing
'Open the File to pickup icon for Loan Calculator
Dim OpenFileDialog1 As New OpenFileDialog
'Set up and display the open File Dialog
With OpenFileDialog1
'Begin in the current Directory
.InitialDirectory = "C:\"
.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
End With
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
mystream = OpenFileDialog1.OpenFile()
If (mystream IsNot Nothing) Then
' I believe the coded goes here but I'm stuck
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (mystream IsNot Nothing) Then
mystream.Close()
End If
End Try
End If
End Sub
This is how I usually do things like this:
Create global variable in the DialogForm:
Public Property sPath as String
or
Public Property imgLogo as Image
To get the Image do this:
imgLogo = Image.FromFile(OpenFileDialog1.FileName)
Or simply do:
sPath = OpenFileDialog1.FileName
instead of
mystream = OpenFileDialog1.OpenFile()
Then when you have done this you close the form by clicking the OK button or whatever you call it.
Then in your main form NewLoanCaculatorForm where you call DialogForm you simply do:
img = DialogForm.imgLogo
or
path = DialogForm.sPath
img = Image.FromFile(path)
Depending on which way you stored the info in the DialogForm.
Also, if you are looking for images I would recommend you not to have .txt in your filter. That would seriously ruin the execution.

Load from file into listbox?

So in my program i am trying to make it so that when you press a button it opens a "choose file" popup(where the user can choose a text file) then after the user chooses it the program will automatically load each line of the textfile into a listbox.
But i have been researching it and the only thing i have been able to find is a file>open thing. So how cold i make it open a "open" dialogue on the press of a button
and since i haven't been able to find anything on the open dialogue i haven't looked for anything on the loading each line of it into a listbox, so if anyone wants ot help me with that it would be great.
and i do not have any code to show you as the rest of my program has no relevance to this
Using FD As New OpenFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Listbox1.Items.Clear
ListBox1.Items.AddRange(IO.File.ReadAllLines(FD.FileName))
End If
End Using
EDIT: Answer on the comment:
If you can use LINQ, then its a one row of code to read all lines from the listbox and write it to a file:
Save using SaveFileDialog and LINQ
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
IO.File.WriteAllLines(fd.filename, (From p As String In ListBox1.Items Select p).ToArray)
End If
End Using
If you can't use LINQ, then you can do this instead:
Save using SaveFileDialog and FOR/EACH
Using FD As New SaveFileDialog()
FD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
If FD.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim FileContent As String = ""
For Each i As String In ListBox1.Items
FileContent &= i & vbCrLf
Next
IO.File.WriteAllText(FD.FileName, FileContent)
End If
End Using
Basically, there are a couple parts here. First, you want to create an Open File Dialog box that prompts the user for where the file is. Here is how you do that:
http://www.homeandlearn.co.uk/net/nets4p6.html
Next, you want to read the text file in line by line into your listbox. Here is how you read your text file (you will need to modify the code to have it add the lines to the listbox instead of doing a Console.WriteLine:
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx
OpenFileDialog from MSDN:
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim myStream As Stream = Nothing
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "c:\"
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Insert code to read the stream here.
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
End If
End Sub
As you can see from the comments, you can read a stream after the user has opened the file. You can then read this stream using, for example, a StreamReader. That will give you the data within the file the user chose. Depending on what you want, you can then parse that data and add it to your listbox.