Can't Delete INI File After Calling GetPrivateProfileString - vb.net

I am having trouble deleting files after calling the GetPrivateProfileString command. I have the following code:
'Read the INI File
sb = New StringBuilder(500)
Select Case FileType
Case "Scanner File"
res = GetPrivateProfileString("ScannerSetings", "ScannerType", "", sb, sb.Capacity, Filename)
Case "Scale File"
res = GetPrivateProfileString("ScaleSetings", "ScaleType", "", sb, sb.Capacity, Filename)
End Select
'If the result is a value store it, otherwise move it to unprocessed
If res <> 0 Then InputArray.Add(sb.ToString)
File.Delete(Filename)
After reading the details from the INI file, as soon as I try to delete the file, I am getting the following error: The process cannot access the file 'R:\Drop\011_11_Scanner' because it is being used by another process.
I cannot even delete these files manually until I exit my application.
Any help would be appreciated.
Thanks

I cannot even delete these files manually until I exit my application.
This clearly shows that the file that Filename points to is locked. As long as it's locked, you won't be able to delete it.
Check your code for any file handles you have opened (eg for writing purposes) and did not close.
If you don't close a file after you've opened it, the file is not released and remains in locked state… which practically means it can not be deleted until (a) you close that file-handle, or (b) you close your program, since that's what's holding the file-handle after opening.
EDIT
The next thing that comes to mind is that VB.NET may need special user access rights to remove the INI on recent Windows versions. You can quickly cross-check that by simply executing your application with elevated user rights (eg via right-click menu; run as admin). I can't imagine that that's actually the problem — but it's worth a shot. Should it indeed be the problem, check (and modify) the permissions on the folder your application and/or INI resides in.

Related

vb.net set windows.old folder permission

Dim myDirectoryInfo As DirectoryInfo = New DirectoryInfo("C:\Windows.old")
Dim myDirectorySecurity As DirectorySecurity = myDirectoryInfo.GetAccessControl()
Dim User As String = "Everyone"
myDirectorySecurity.AddAccessRule(New FileSystemAccessRule(User, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow))
myDirectoryInfo.SetAccessControl(myDirectorySecurity)
I have a program that deletes junk files on the computer.
I want to delete the files in windows.old but the above code doesn't work.
Can you help me?
Windows.old is created and maintained for a short period of time in case you want to roll back to a previous install. It normally contains all the files from a previous install.
It should go away by itself, but if not, go to Settings, System, storage and click on the drive at the top of the page. Run down to Temporary files and it should be listed as Previous version of Windows. See if you can delete it there.
If you have deleted parts of it manually, no telling what it will do.
I would not recommend writing code to handle this as it isn't a folder that should come back after you deal with it once.

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.

multiple programming try to access same text file

I had created and text file using (AFL SCRIPTING LANGUAGE) this script will update (write) to a text file every 5 seconds. I will try to read file using vb.net, when I run the vb.net code form visual studio, everything works fine but (AFL script not able to update the text file), here is my vb.net code:
Dim FILE_NAME As New FileStream("C:\myreport\myfile.TXT", FileMode.Open, FileAccess.Read, FileShare.Read)
REM Dim FILE_NAME As String = "C:\myreport\myfile.TXT"
REM Dim TextLine As String
REM If System.IO.File.Exists(FILE_NAME) = True Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
MYSTRING(I) = objReader.ReadLine()
I = I + 1
Loop
REM End If
When I run the code above, ( AFL script not able to update the text file),
Put simply:
When I run the vb.net code (for accessing the text file), AFL script not able to update.
I had share read/write the folder (where the text file exists), no effect, same problem I am facing.
Unchecked "Enable visual studio hosting process", still problem not solved.
In .NET, the FileSystemWatcher class can help you with this problem. You can read the file each time the file watcher says that the files has changed. Here is the reference documentation for it.
You cannot read and write to a file from two processes at the same time. Well, technically you can, but it can lead to a race condition which is bad.
You need to implement some kind of shared locking mechanism around the file to prevent your two programs from fighting over it. Or, if you can guarantee that the consumer VB.NET program will have the file open for less than 5 seconds, you can go with MrAxel's solution and simply have the VB.NET program read the file every time it is updated.

UnauthorizedAccessException with File.AppendAllText in VB.NET

I have recently started getting System.UnauthorizedAccessException errors when using File.AppendAllText to write to a shared drive on the network. I think there were some changes to the network when this happened. The code in my application hasn't changed.
I have asked our IT dept to grant me full permission to the folder. I can see I have permissions for Modify, Read & Execute, Read, Write under my username if I navigate to the file and look at the Security tab under properties. I am also part of a group with read, write and modify permissions to the folder.
This works without error in the same folder:
File.WriteAllText(myFile, myText)
This generates a System.UnauthorizedAccessException error when it reaches the AppendallText:
If File.Exists(myFile) = False Then
' Create a file to write to.
Dim createText As String = logTime & " " & report_data
File.WriteAllText(myFile, createText)
Else
Dim appendText As String = logTime & " " & report_data
File.AppendAllText(myFile, appendText)
End If
I have tried deleting the file and creating it again, that made no difference.
I tried File.SetAttributes(myFile, FileAttributes.Normal)
The IT dept can't see what the problem is.
I can manually open, change and modify the file. The problem only arises if I am trying to do this programmatically.
Is there a different 'user' which tries to modify files? Could the file be open somehow, or would that generate a different error?
I'm using VB.NET 2012, .net framework 4.5, Windows 8.1
The network changes were the problem. It doesn't seem possible to resolve this as it is. Instead I made a copy of the text data, append my new text to that, delete the file, and save the updated text to a new file.

Cannot delete just created file

My application can create a directory, put a file in it from a ZIP file and then remove the ZIP file.
When I then try to delete that file, I get an Access Denied error even though nothing was done with it.
Here is the code:
File.WriteAllBytes(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip", op.Documenten)
Using zp As New ZipFile(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip")
zp.FlattenFoldersOnExtract = True
zp.ExtractAll(OpslagLocatieDocumenten + myTicketNummer.ToString, ExtractExistingFileAction.OverwriteSilently)
zp.Dispose()
End Using
Try
For Each itm As String In Directory.GetFiles(OpslagLocatieDocumenten + myTicketNummer.ToString)
Try
File.Delete(itm)
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
It looks a bit messy right now, but that is for testing purposes.
In the for-next part, right after writing the file from the ZIP, I try to delete the files.
At the moment there are two files in the directory, one ZIP and one PDF document from the ZIP.
The first file in itm is the PDF, it errors with an ACCESS DENIED.
The second file in itm is the ZIP which gets deleted.
The PDF is 311 kb in size.
Via Windows explorer I can delete it without any problem, even with the application still running.
Why is my file being locked?
What can I do to by-pass or remove this lock?
rg,
Eric
Found the problem.
The file that was added to the ZIP had it's attribute set to READ ONLY.
So when the application writes the file, windows would, as it should, not allow the application to delete it.
Unfortunately, windows does allow to delete the file via windows explorer without a message that the file is read only.
Have you also tried the File.Kill(fileLocation) method?