File created and opened with Streamwriter vanishes when end using is hit - vb.net

The following code, in a Console app
Using (System.IO.File.Create(Path & "\" & file))
End Using
Using FSW As New System.IO.StreamWriter(Path & "\" & file, False)
FSW.WriteLine(header)
creates a file and opens it to write with streamwriter. I don't think I actually need to create the file first. I think that the opening for reading would do that for me. The Console app does some stuff and then closes/disposes of the stream writer with an end using. A couple of things:
This code is being called inside a Sub that is inside a while
loop in Main.
The first time through the loop the files are created in the correct
directory. the directory to write to (path) is passed to the Sub
from the for each loop.
The paths and file names are correct: I have written them with
the immediate window and cut and pasted them into the file explorer.
They are pointing to the right place.
When the create is hit, the file appears in the directory.
When the end using is hit it vanishes. When the streamwriter object
is created the file appears in the directory. When it's end using
is hit the file vanishes.
This is exactly the opposite problem from what most people have in where the fail to .close .flush .dispose or end using a stream writer. Please also keep in mind that this code worked once. And as fore mentioned works the first time through the loop.

Related

Problem handling errors with FileSystemWatcher

To start with it has been many years since I have done much programming, probably about 15 years, in fact VB 6 was still being taught then so I'm not up to date on anything and can get lost in what I'm reading but I am trying. I'm using Visual Studio 2019 and trying to create a VB Windows Forms App that uses the FileSystemWatcher. Unfortunately the only solutions to my problem that I could find are in C#. I tried to transfer them to my app but couldn't get them to work. Actually Visual Studio wasn't happy with what I put in and wouldn't run at all, probably due to incorrect syntax.
This part of my little app is supposed to copy a file that another program creates, while the other program is running, and place the copy in another folder. It seemed simple, detect that the file had been changed and then copy the changed file. Well I came across a few problems.
The first problem is that if I create an empty file the code works most times with no problems but occassionally 2 copies of the file are created. I could live with that but.
If I replace the empty file with a larger file, the file that it is meant to copy, then it can make 3 or 4 copies and most times produces a messagebox telling me that it can't access the file because it is in use. The main program is also minimised to display the error message, which I don't want.
Even if my app is the only program running and I replace the watched file manually with the larger file I still get the file in use error, so I am assuming that the event has been triggered twice and one of them is the process that is using the file and causing the error.
If I tell the error message to cancel then my program continues and produces only 1 copy of the file. Which is what I do want.
The second problem is that the file being copied is also accessed by another program for a short period imediately after it has been changed and this also causes an extra few copies of it to be made and sometimes a file in use error message box appears, and again the main program is minimised to display the error message. I originally had other IO.NotifyFilters in place that weren't really necassary and thought that they may have been triggering the errors so I removed them, but it made no difference.
The most common error is that the file is in use but there has also been the odd "Unhandled exception has occured in your application. could not find file.". The only reason that I can think of for this error is that the file may have been renamed to a backup file and a new version created by the main program at the exact time my program tried to access it.
From what I have read the FileSystemWatcher can trigger multiple times and I presume that this is what is causing the duplicate copies from both problems.
I need my app to make only 1 copy without the error messagebox appearing as this program needs to run in the background with no user input. Essentially this part of my app is an external program to backup a file when the file changes because the main program changes this file often but only seems to back up the file every few hours.
The following code is what I have used but nothing that I have tried has caught the error so I removed the error event handler. This code was copied from something else that was similar and in C# then modified for my purpose. I thought that the {} were used for C# not VB but it seems to work and if I take them out it won't.
My code for the FileSystemwatcher is:-
WatchFile = New System.IO.FileSystemWatcher With {
.Path = Path.GetDirectoryName(strArkMapFileNamePath),
.Filter = Path.GetFileName(strArkMapFileNamePath),
.NotifyFilter = IO.NotifyFilters.LastWrite
}
' add the handler to each event
AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite)
'Set this property to true to start watching
WatchFile.EnableRaisingEvents = True
The event handler is:-
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Copy the Save file to a new folder and rename it.
My.Computer.FileSystem.CopyFile(
strArkMapFileNamePath,
strBackupPath & "\" & strArkMapFileName & "_" &
DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark",
Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs,
Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
End Sub
I added an error event handler after AddHandler WatchFile.Changed, New FileSystemEventHandler(AddressOf OnLastWrite) but that did nothing.
I tried to add an on error statement before the end sub and that did nothing either, I presume because the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, caught the error first.
I got frustrated and tried to add a statement before the Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, but it didn't like that and I didn't expect it to work.
So how do I catch the errors before the FileSystemWatcher acts on the error?
I don't know what I am doing wrong so any help would be appreciated.
Also if anybody could offer code for what I need to do can it please be code for a Windows Forms App because I don't seem to have much luck in converting C# or anything else.
Edit
I have replaced the My.Computer.FileSystem.CopyFile with the File.Copy method as suggested and added a few extra bits..
Private Sub OnLastWrite(sender As Object, e As FileSystemEventArgs)
'Verify that source file exists
If File.Exists(strArkMapFileNamePath) Then
'Copy the Save file to a new folder and rename it.
Dim i As Integer
For i = 0 To 3
Try
' Overwrite the destination file if it already exists.
File.Copy(strArkMapFileNamePath, strBackupPath & "\" & strArkMapFileName & "_" & DateTime.Now.ToString("dd.MM.yyyy_hh.mm.ss") & ".ark", True)
i = 3
' Catch exception if the file was already copied.
Catch copyError As IOException
'If copy failed reset counter
i += 1
End Try
Next
End If
End Sub
Although this shouldn't be required because this is done before the FileSystemWatcher is enabled I have added an If statement to check that the files exists before attempting to copy the file.
I'm not entirely happy with the loop but I know under normal conditions that it's not going to be an endless loop.
Is there a way to just catch the specific errors that I would need to deal with or will it be fine the way it is?
I will probably still need to work out how to stop the FileSystemWatcher from sending more than 1 event or somehow make multiple events appear as 1.
The If statement was the last thing that I added and for some reason the program now seems to only make 1 copy and appears to be faster.
The other external program that accesses the file being copied must be slower to react than my program because now it displays a message that it's waiting until my program has finished copying the file.
My program is now performing as it was intended but I believe that it is just a matter of timing rather than the correct code.

vba Dir(sharePointPath) return empty after saveAs unless manually refresh the folder

I'm saving a excel file one share Point into text file. after the saving, I wanna check Dir(sharePointPath).
It will always return "" unless I manually refresh the corresponding folder.
the code would be like the following:
ActiveWorkbook.SaveAs sharePointPath, xlTextWindows
ActiveWorkbook.Close
While Dir(sharePointPath) = ""
MsgBox "not exist"
Wend
The reason I wanna check Dir(sharePointPath) is that I wanna open that file later
open sharePointPath for binary access read as
which always override the text file because open can't find the file.
what should I do to fix this problem?
EDIT:
sharePointPath = {server}\rule_books\Shared Documents\Rule books\NAME - Demo and Testing Client\Text Files\test.txt before saveAS and after close.
dir(sharePointPath) = "" before and after. occasionally dir(sharePointPath) = test.txt.
but if I wait for a while after close to excute dir(sharePointPath), it will return test.txt more often. i guess vba take some time to write and show the new file.
I gave up, and create a local tmp file on user's end machine for work around

Program not able to write to a newly made text file

After some great arguments made by other users in this question: How to write to a text file inside of the application, I decided to not use a resource file, instead create a file in a folder & then read/write from there.
Although, for some reason, I can't seem to write to the file in question, it keeps throwing an exception telling me the file is already in use by another process.
Here's the code which I use for writing to this file.
If System.IO.File.Exists(credentials) Then
Dim objWriter As New System.IO.StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
Else
System.IO.Directory.CreateDirectory(Mid(My.Application.Info.DirectoryPath, 1, 1) & ":\ProgramData\DayZAdminPanel")
System.IO.File.Create(credentials)
Dim objWriter As New System.IO.StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End If
Any ideas on how I can write to the text file in question?
There's a good chance that a previous iteration of your application failed to properly close access to the file in the StreamWriter. Since your constructor is set to overwrite (and not append) to the file, this could be the source.
Try setting up your application with a "Using" statement to properly open/close the file:
If System.IO.File.Exists(credentials) Then
Using objWriter As StreamWriter = New StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End Using
Else
System.IO.Directory.CreateDirectory(Mid(My.Application.Info.DirectoryPath, 1, 1) & ":\ProgramData\DayZAdminPanel")
System.IO.File.Create(credentials)
Using objWriter As StreamWriter = New StreamWriter(credentials, False)
objWriter.WriteLine(remember)
objWriter.Close()
End Using
End If
It does look rather redundant to have a Using block and a close statement, but this ensures access to your file even if an exception occurs.
You are trying to create a directory in the common application data directory. This directory should be found using the Environment class methods and enums because is different between operating systems. However you use the value credentials for the filename. I suppose that you want to store your datafile in the common application directory and not in a place where there is no permission to write data files (Like C:\program files (x86)).
Then, to avoid problems with file stream not correctly closed try to use the Using statement that assures a correct closure and disposal of your file resource (No need to call close inside a Using).
Also, notice that StreamWriter is perfectly capable to create the file if it doesn't exists or if you wish to overwrite the previous contents (passing false for the Append flag).
So your code could be reduced to these lines.
' Get the common application data directory (could be different from Win7 and XP)
Dim workDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
' Combine with your own working data directory
workDir = Path.Combine(workdir, "DayZAdminPanel")
' Create if not exists
If Not Directory.Exists(workDir) Then
Directory.CreateDirectory(workDir)
End If
' Create/Overwrite your data file in a subfolder of the common application data folder
Dim saveFile = Path.Combine(workDir, Path.GetFileName(credentials))
Using objWriter = New System.IO.StreamWriter(saveFile, False)
objWriter.WriteLine(remember)
End Using
File.Create returns an opened FileStream that you should be passing into the StreamWriter constructor on the subsequent, rather than passing the filename again, or you can just omit the File.Create call altogether.
You might want to look into a Using block for the StreamWriter so it gets predictably closed.

Will A Line Of Code Finish Before Executing The Next Line Of Code?

The following codes is moving a file as long as the file doesn't already exist. If it does, it won't move the file.
My question is regarding the File.Move. When will the msgbox display? Will it display once the file is completely moved or will it display right after the File.Move line is executed.
Depending on the file size, it may take awhile to move the file and thus I don't want the msgbox to display until the file is moved completely.
Is there a better way of doing this?
For Each foundFile As String In My.Computer.FileSystem.GetFiles("C:\Temp\", FileIO.SearchOption.SearchAllSubDirectories, "*.zip")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
If My.Computer.FileSystem.FileExists("C:\Transfer\" & foundFileInfo.Name) Then
Msgbox("File already exists and will not moved!")
Exit Sub
Else
File.Move(foundFile, "C:\Transfer\" & foundFileInfo.Name)
Msgbox("File has been moved!")
End If
Next
Accordingly to this source, the File.Movecall is synchronous, which means that your msgbox will be shown only after the file is moved, regardless of its size.
For completeness, if you don't want to block the UI, you can try something like this:
' This must be placed outside your sub/function
Delegate Sub MoveDelegate(iSrc As String, iDest As String)
' This line and the following go inside your sub/function
Dim f As MoveDelegate = AddressOf File.Move
' Call File.Move asynchronously
f.BeginInvoke(
foundFile,
"C:\Transfer\" & foundFile,
New AsyncCallback(Sub(r As IAsyncResult)
' this code is executed when the move is complete
MsgBox("File has been moved!")
End Sub), Nothing)
or you can explore the new async / await instructions.
File.Move is a synchronous operation, so the application will not execute the next line of code (your messagebox) until the move is complete.
As you indicated, if the file is large (and you are moving across drives) the messagebox will not show up until the file move is complete. This can create a poor user experience, as your GUI will appear to be non-responsive during this time.
I would recommend taking the time to learn how to utilize background threads or async/await calls to perform the operation in the background.
There is a good article on Asynchronous IO on MSDN: http://msdn.microsoft.com/en-us/library/kztecsys.aspx
Finally you could also use the FileSystem object's MoveFile method, which can pop up a file move UI for you, if you are just worried about keeping your UI responsive:
FileSystem.MoveFile(sourceFileName, destinationFileName, UIOption.AllDialogs)
unfortunately, the code is executed line after the other so the Msgbox will pop up as long as the file has been completely moved.
if you want to monitor the progress, visit this link for more details.
The Message box will be displayed after the file is completely moved irrespective of the file size.
Unless a method is asynchronous, a line of code will always finish executing before proceeding with the next line.
Note, if the file move is slow, and it holding up your program is a Bad Thing, then you could do the move in a background thread using for instance a BackgroundWorker.

the process cannot access the file because it is being used by another process in vb.net

help me.. i'm new in visual basic....
when i'm running the update it shows the error
The process cannot access the file 'C:\Documents and Settings\Macky\My Documents\Visual Studio 2008\Projects\Marcelo 2.2.3\Marcelo\bin\Debug\Students\MIC953867.jpg' because it is being used by another process.
my code is this
Public Sub copingfile()
If inFileName = Nothing Then
studpic.Image = Nothing
Else
outFileName = inFileName
pos = inFileName.LastIndexOf(".")
If (pos > 0) Then
outFileName = outFileName.Substring(0, pos)
End If
outFileName += ".jpg"
str = Application.StartupPath & "\Students\"
saveJPEGFile.FileName = str & StudID.Text & ".jpg" '& outFileName
fil1.Copy(inFileName, saveJPEGFile.FileName, True) 'the error shows here...
outFileName = saveJPEGFile.FileName()
End If
End Sub
I can save new student information with picture.. but when it comes in updating the picture these codes didn't work......
fil1.Copy(inFileName, saveJPEGFile.FileName, True)
You're attempting overwrite a file that's open or being used. If the file is open in a viewer/editor, then it can't be copied over. Either you opened it manually, or did so through code and it's still "attached" to something running.
If it's not open in a window, try stopping your code and deleting that file manually. If you can, it's pretty obvious something in code is still using it when you get to the line that errored. You'll need to figure out where that file is still being used (Open stream somewhere? Open in VS, itself?), as it doesn't appear to be in the code you provided.
You are going to need to show more code, you are using variables not in your code listing. Plus you do not show the code that originally saves your image.
But here is my guess...are you sure you closed the file when you saved it for the first time? You cannot generally copy to, or from, a file that is open.
(Files can be opened as shared, but I don't think you are doing that).
Post more code if you get a chance.