I have a program written in VB.NET which stops a service that uses file x, modifies x, and restarts the service.
I have modified my code for testing so that it just reads in the file as a string and immediately writes it back out.
Shell("net stop " & SERVICE_NAME, , True)
Dim myReader As System.IO.StreamReader
myReader = My.Computer.FileSystem.OpenTextFileReader(x)
fileString = myReader.ReadToEnd()
myReader.Close()
Dim tempFile As System.IO.StreamWriter
tempFile = My.Computer.FileSystem.OpenTextFileWriter(x, False)
tempFile.Write(fileString)
tempFile.Close()
Shell("net start " & SERVICE_NAME, , True)
The stopping of the service is no problem, and modifying the file is no problem, but when the service starts it stops immediately because, as best I can guess, the file is in use. Even when I try to start the service manually, it stops immediately. However, I found that I can open file x, click save without modifying anything, close the file, and start the service and everything works correctly.
If I comment out the writing part, everything works fine.
Also, the file I’m modifying has a .conf file extension. I don’t know if this is relevant.
Any suggestions on what could be causing this behavior?
Thanks,
B.J.
To avoid the BOM you need to specify an encoding that doesn’t have one, use
System.Text.Encoding.DefaultWhile that convenience method is nice I still prefer to manually create a FileStream object so I can set the sharing flag ensuring that no one accesses my file until I’m done with it: