Issue with deleting a binary file - c#

I'm trying to delete a binary file from a directory in C#. But the File.Delete() method seems to work in misterious ways.
You see, when I try to delete the specified file from my directory, it doesn't work and the file is not deleted. However, when I open the directory where I have the file and then I execute my project to try to delete the file again, the file IS actually getting deleted and does not appear afterwards. What can be the issue?
This is my code:
currentDB.listTab = delTab.backup;
String fullPath = path + "\\" + delTab.delete;
File.Delete(fullPath);
txtStats.Text = "Deleted";
load_tables();
show_files();
I ask for the name of the file (delTab.delete) on a different window, and then I return the name in order to delete the file.

Related

Files disappear after they fail to be moved

We have a process where people scan documents with photocopiers and drop them in a certain directory on our file server. We then have a hourly service within an .NET Core app, that scans the directory, grabs the file and moves them according to their file name to a certain directory. Here comes the problems.
The code looks something like that:
private string MoveFile(string file, string commNumber)
{
var fileName = Path.GetFileName(file);
var baseFileName = Path.GetFileNameWithoutExtension(fileName).Split("-v")[0];
// 1. Check if the file already exists at destination
var existingFileList = luxWebSamContext.Documents.Where(x => EF.Functions.Like(x.DocumentName, "%" + Path.GetFileNameWithoutExtension(baseFileName) + "%")).ToList();
// If the file exists, check for the current version of file
if (existingFileList.Count > 0)
{
var nextVersion = existingFileList.Max(x => x.UploadVersion) + 1;
var extension = Path.GetExtension(fileName);
fileName = baseFileName + "-v" + nextVersion.ToString() + extension;
}
var from = #file;
var to = Path.Combine(#destinationPath, commNumber,fileName);
try
{
log.Info($"------ Moving File! ------ {fileName}");
Directory.CreateDirectory(Path.Combine(#destinationPath, commNumber));
File.Move(from, to, true);
return to;
}
catch (Exception ex)
{
log.Error($"----- Couldn't MOVE FILE: {file} ----- commission number: {commNumber}", ex);
The interesting part is in the try-block, where the file move takes place. Sometmes we have the problem that the program throws the following exception
2021-11-23 17:15:37,960 [60] ERROR App ----- Couldn't MOVE FILE:
\PATH\PATH\PATH\Filename_423489120.pdf ----- commission number:
05847894
System.IO.IOException: The process cannot access the file because it is being used by another process.
at System.IO.FileSystem.MoveFile(String sourceFullPath, String destFullPath, Boolean overwrite)
at System.IO.File.Move(String sourceFileName, String destFileName, Boolean overwrite)
So far so good. I would expect that after the file cannot be moved, it remains in the directory from it was supposed to be moved. But that's not the case. We had this issue yesterday afternoon and after I looked for the file, it was gone from the directory.
Is this the normal behaviour of the File.Move() method?
First to your question:
Is this the normal behaviour of the File.Move() method?
No, thats not the expected behaviour. The documentation says:
Moving the file across disk volumes is equivalent to copying the file
and deleting it from the source if the copying was successful.
If you try to move a file across disk volumes and that file is in use,
the file is copied to the destination, but it is not deleted from the
source.
Your Exception says, that another process is using the file in the same moment. So you should check, whether other parts of your application may performs a Delete, or someone (if this scenario is valid) is deleting files manually from the file system.
Typically, File.Move() only removes the source file, once the destination file is successfully transferred in place. So the answer to your question is no, it cannot be purely the File.Move(). The interesting part is, why is this file locked? Probaby because some file stream is still open and blocking access to the file. Also, do you have multiple instances of the copy process services running? This may cause several services trying to access the file simultaneously, causing the exception you posted.
There must be a different cause making the files disappear because the File.Move() will certainly not remove the file when the copy process did not succeed.
For debugging purposes, you may try and open the file with a lock on it. This will fail when a different process locks the file providing you a little bit more information.

ASP.NET CORE, How read all files in a folder that is used from another process

im trying to read a folder from a remote machine, inside this folder there are many txt files.
The machine is writing every time new datas inside the folder.
string str = "";
try
{
DirectoryInfo d = new DirectoryInfo(#"\\192.168.1.209\user\HST\");
FileInfo[] Files = d.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
}
catch (Exception pp)
{
System.IO.File.WriteAllText(GlobalVariables.errorFolderLocation + "erroreLettura.1.209.txt", pp.ToString());
}
This is my code, I don't understand how to get these datas, because i get this error: "the system call level is not correct".
For example, if i try to delete the folder or a file, i get error because it's already used by another process.
So, is there a solution to "bypass" this error?
EDIT 1:
I need read every row of every file, i get the error on DirectoryInfo.
If i acces on the folders and files it works fine.
I need read this folder/files in 3 different machine, but only in this (192.168.1.209) not working, and its the only machine where i get error when i try to delete a file
Unfortunately, you are not able to delete a file which is in use by another process or delete a folder that contains a file in use, or whatever other operation that has not been specified to be accessed on the other process. In order to achieve this, the process which has the file in use, must open it with a share access, FileShare from System.IO .NET library.

How to check if a file exists or not in the directory the executable is?

How can I check if a file exists or not in the directory the executable is?
I know how I could code it like this.
string path = Application.StartupPath + "config.cfg"
if(!FileExists(path))
{
//create the file
}
But the problem I am facing is that, the file is created every single time, even when the file exists, overwriting the data of the cfg file with the default ones.
You are not creating the possible file path properly. Use Path.Combine like:
string path = Path.Combine(Application.StartupPath, "config.cfg");
You are getting a path without terminating \ from Application.StartupPath, later you are concatenating the file name to it, This will create an invalid path, and since that doesn't exist, you check fails.
Just to show, the actual reason for getting the error, you can fix your code like:
string path = Application.StartupPath +"\\"+ "config.cfg";
But, do not use the above code, instead use Path.Combine to join multiple path elements.

Directory.Move(): The process cannot access the file because it is being used by another process?

In my below code, I am trying to move all my .doc files located in one folder to another. In production, this will be moving files generated into created folder C:\Temp\ to a network folder that has a database job which every 5 minutes moves the files from the network folder into our document imagining archive system.
When trying my below test code, I receive "The process cannot access the file because it is being used by another process."
CODE:
public void moveLocalToCommitFYI()
{
// MOVE DOCS FORM TEMP FOLDER TO COMMITFYI FOLDER
string dirSource = #"C:\Users\NAME\Desktop\CommitTest\MoveTest\";
string dirDest = #"C:\Users\NAME\Desktop\CommitTest\MoveTest\DestTest\";
try
{
Directory.Move(dirSource, dirDest);
}
catch (Exception ex)
{
MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
}
}
What appears strange to me is that when I specify a single source file outright and it's destination, code functions fine:
public void moveLocalToCommitFYI()
{
// MOVE DOCS FORM TEMP FOLDER TO COMMITFYI FOLDER
string dirSource = #"C:\Users\NAME\Desktop\CommitTest\MoveTestFile.doc";
string dirDest = #"C:\Users\NAME\Desktop\CommitTest\MoveTest\MoveTestFile.doc";
try
{
Directory.Move(dirSource, dirDest);
}
catch (Exception ex)
{
MessageBox.Show("Source:\t" + ex.Source + "\nMessage: \t" + ex.Message + "\nData:\t" + ex.Data);
}
}
Surely there is a way to move all my .doc files from the one directory to the other without needing to loop through and specify each individual file name?
EDIT:
Made the modification of having my destination folder be a different folder on my desktop instead of a sub-folder. dirSource contained 5 word documents and the destination directory (\MoveTest\ on my Desktop) contained no files:
string dirSource = #"C:\Users\NAME\Desktop\CommitTest\MoveTest\";
string dirDest = #"C:\Users\NAME\Desktop\MoveTest\";
This generated "Cannot create a file when that file already exists".
Based on this, I assumed that the code is actually MOVING the set directory folder and all it's contents from one location to another, so I modified my code to the following:
string dirSource = #"C:\Users\NAME\Desktop\CommitTest\MoveTest\";
string dirDest = #"C:\Users\NAME\Desktop\MoveTest2\";
This got rid of my sub-folder \MoveTest\ within \Desktop\CommitTest\ and created folder \Desktop\MoveTest2.
Is there a way for me to move the contents of the folder without getting rid of the source folder and place them into an already created destination?
Your test code is trying to move the entire directory into a directory inside itself. This is not a valid operation. Your actual code is probably trying to move the whole Temp directory to another location. This is not the same as moving all files inside it to another directory.
You'll have to loop through all file names and move each file individually.
var files = Directory.EnumerateFiles(dirSource, "*.doc")
.Select(path => new FileInfo(path));
foreach (var file in files)
file.MoveTo(Path.Combine(dirDest, file.Name));
If you find that the individual moves add too much overhead to the network traffic (especially important if this is a slow Internet connection and not a fast local connection), you might want to zip up all of your doc files (e.g. with ZipFile) before transmitting them to the server, and then have the server unzip them. This compression will probably lower the overall size, and transmitting one file instead of many will reduce the network overhead.
You cannot move a folder below itself. You need to find all its contents and move them. Or do this: rename MoveTest to MoveTest2, create a new MoveTest directory, and now you can move MoveTest under it.

Deleting an unlocked file in C#

In a C# program, I am creating files. I want to delete one file using this command:-
File.Delete(killFile);
The killFile has a value = "C:\Documents and Settings\MehdiAnis\My Documents\outfile_0020.csv"
The killFile is an existing file.
After I run Delete command, file is still in the Directory. Right after delete I added FileInfo code to check if the file exists,
FileInfo fi = new FileInfo(killFile);
Now, fi.Exists shows false
I am not sure what's wrong, can it be permission issue? I just wrote the file in my own folder, why can't I delete it? Once the file is created I am not opening it or doing anything with it, so it should not be locked.
What could be wrong and where else should I be looking?
Per the screenshot you posted at http://i548.photobucket.com/albums/ii341/MehdiAnis/cprob.jpg
In your screen shot, the explorer window is showing a file with name eding in "_0020.csv" . You are passing in a filename ending with "_20.csv", according to the debugger window. You are calling File.Delete with the name of a file that doesn't actually exist, and so no file is deleted.
You will want to format your "killFile" variable with 0 padding. I assume you are adding some counter to it like killfile = killFile + i.ToString(). Try killfile = killFile + i.ToString("0000")
According to MSDN, "If the file to be deleted does not exist, no exception is thrown."
You may want to check for existence of the file to be deleted using File.Exists before trying to delete it. I think your problem is the file you are expecting to delete isn't the file that you see in the folder.

Categories