Ramyy

Hi all

I am trying to create a notepad text file and write some data to it but it gives me an error saying:

The process cannot access the file because it is being used by another process

but i don't have anything else using this file, so don't know why it won't let me.

heres my code with comments

Code Snippet
Private Sub File_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles File_Button.Click


Dim filename As String = "C:\Documents and Settings\Ramyy\Desktop\RFID.txt"
IO.File.Create(filename)

' We can test this by seeing if the file exists.
If IO.File.Exists(filename) = False Then
' The file does not exist.
' Here's a string variable that stores the error message.

Dim messageForUser As String = String.Format("The file ""{0}"" does not exist!", filename)
' Show the message
MessageBox.Show(messageForUser, "Noooooo!", MessageBoxButtons.OK)
' Exit the sub.
Exit Sub
End If
' Is it a text file
If IO.Path.GetExtension(filename) <> "txt" Then
' It might not actually be a problem, text files don't have to have a txt extension.
Dim messageForUser As String = String.Format("The file ""{0}"" is not a text file!", filename)
End If
' Ok, so the file exists, which is good.
' We need a TextWriter to Write Text.
' We set it to nothing for now to stop a nag in visual studio express.
Dim textWriter1 As IO.TextWriter = Nothing
' We might not be able to open the file though (especially on vista!)
' So, instead of writing code to open it, we will write code
' to TRY to open it.
Try
' Open the file, in a special way - just for appending text:
textWriter1 = IO.File.AppendText(filename)
' Use the textWriter to write something
If FragileCheckBox.Checked = True Then
textWriter1.WriteLine("Fragile")
Else
textWriter1.WriteLine("Not Fragile")
End If
textWriter1.WriteLine(Weight_of_BaggageTextBox.Text)
textWriter1.Write(Flight_NumberTextBox.Text) ' write text without a newline.
textWriter1.Write(Environment.NewLine) ' write just a newline.
textWriter1.WriteLine(DestinationTextBox.Text) ' write text and a newline
textWriter1.Write(My.Computer.Clock.LocalTime.Day.ToString)
textWriter1.Write(" ") 'write space
textWriter1.Write(My.Computer.Clock.LocalTime.Month.ToString)
textWriter1.Write(Environment.NewLine) ' write just a newline.
textWriter1.Write("This file is called " & filename)
MessageBox.Show("Things have been written to the file.")
Catch ex As Exception
' If there was a problem Creating the TextWriter, then we can
' "catch" then problem here.
' ex has the information for the user in it's message property.
' I'll do this on two lines...
Dim messageForUser As String = "Could not open file: {0}{1}"
' replace {0} with a new line, and {1} with the error message, and assign back to messageForUser:
messageForUser = String.Format(messageForUser, Environment.NewLine, ex.Message)
MessageBox.Show(messageForUser, "Eeek!", MessageBoxButtons.OK)
Finally
' This is part of the try...catch... block.
' The code in here will run even if there was an error.
' We use it to get rid of the textWriter, if it exists:
If textWriter1 IsNot Nothing Then textWriter1.Dispose()
End Try
End Sub

I am assuming it might be something im forgetting in code.

Thanks for your help in advance

Rami



Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

LouieG

Hi Rami,

if you remove the code from here:-->>

IO.File.Create(filename)
If IO.File.Exists(filename) = False Then
Dim messageForUser As String = String.Format("The file ""{0}"" does not exist!", filename)
MessageBox.Show(messageForUser, "Noooooo!", MessageBoxButtons.OK)
Exit Sub
End If
' Is it a text file
If IO.Path.GetExtension(filename) <> "txt" Then
Dim messageForUser As String = String.Format("The file ""{0}"" is not a text file!", filename)
End If

<<-- to here

then your code will work.

it is a pity i don't know what you really want to do - 'cos then i could have made suggestions

Louie






Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

bdbodger

After reading your post I decided to find out what a textwriter is exactly . The help file describe it as

TextWriter is the abstract base class of StreamWriter and StringWriter, which write characters to streams and strings, respectively

One being a stream writer the other being a string writer .

Code Snippet

Dim aStringWriter, aStreamWriter As TextWriter
aStringWriter = New StringWriter()
aStreamWriter = New StreamWriter("InvalidPathChars.txt")

From what I gather reading the help file one writes to a string and the other to a file stream . In looking at the other part of your code

textWriter1 = IO.File.AppendText(filename)

Dim path As String
Dim returnValue As StreamWriter

returnValue = File.AppendText(path)
It does not look to me like you have defined textwriter1 as a streamwriter rather than a stringwriter . It also looks to me like you maybe able to use a streamwriter without defining a textwriter but I don't know like I said I only look at the help files so once you have it working I would like to see what the solution was .




Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

Dave299

I think the problem lies in this line:

IO.File.Create(filename)

File.Create is a function which returns a filestream which should be closed when you have finished with it. You are not doing that. Change it to this and the problem appears to go away:

Dim S As IO.FileStream = IO.File.Create(filename)

S.Close()

However as LouieG has pointed out you don't need to do it like that anyway. The TextWriter will create the file if it doesn't already exist.





Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

bdbodger

Hi just looking at the example in the help files again I notice that after they create the text file

Code Snippet

Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter

' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
sw = File.CreateText(path)

That they flush the streamwriter and close it before using it with the File.AppendText method which seems to open the file again only this time for append after they wrote some text to when they created it then closed it .

** I see dave posted while I was writing . Anyway what is the purpose of the textwriter is it just that both the string writer and stream writer can use the same threads Is threads the right word to describe subs and functions





Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

Ramyy

Awesome work guys Smile

Really impressed with answers..

Ive implemented Louie's idea and it worked beautifully Smile

Also read about streamwriter and stringwriter (bdbodger's influence) and found that u can do it with simple code such as:

Code Snippet

Dim theFileStream As New FileStream(filename, FileMode.Append, FileAccess.Write)

Dim theStreamWriter As New StreamWriter(theFileStream)

theStreamWriter.Close()

theFileStream.Close()

Which is similar to what Dave said about closing the filestream.

Again thanks for all your help..

Ramyy





Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

Dave299

"Anyway what is the purpose of the textwriter is it just that both the string writer and stream writer can use the same threads Is threads the right word to describe subs and functions "

The Help seems to be a little unclear on this one. TextWriter is an abstract base class. Being abstract it should never be instantiated. But to quote Help:

"Create an instance of TextWriter to write an object to a string, write strings to a file.............."

I think what they mean is create an instance of StreamWriter or StringWriter, both of which inherit from TextWriter. As you say that means they can use the methods provided by the base class.





Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

bdbodger

I see I think it is a bit clearer now that you mention inheritance it was this

Code Snippet

Shared Sub WriteText(aTextWriter As TextWriter)
aTextWriter.Write("Invalid file path characters are: ")
aTextWriter.Write(Path.InvalidPathChars)
aTextWriter.Write("."C)
End Sub

That made me think that it can be called by both the stream writer and string writer but if it was defined as either one then it can only be called by the same type . Not that I really see much use for it but you never know there maybe a situation where you would need to do it this way .




Re: Visual Basic Express Edition Creating a text file and writing data to it, then saving it on desktop

Dave299

This is where the Object Browser comes in useful.

Fire it up (F2) and navigate down to System.IO.TextWriter. Then have a look at the Write methods. You will see that they are all marked as Overridable.

Now go to the StreamWriter and look at the same methods. You will see that some of them are still marked as Overridable and that these are a member of TextWriter. For these methods using them uses the methods as defined in the base class TextWriter.

However you will see that some of them are marked as Overrides and that these are members of StreamWriter. This means that the StreamWriter class has overrided the base class implementation of the method and is providing its own method.

So if you use a StreamWriter and want to write a string then you will use the method provided by the StreamWriter but if you want to write a Single then you will actually be using the method provided by TextWriter.