Deleting an unlocked file in C# - 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.

Related

FileInfo.CopyTo how to detect overwrite

file.CopyTo(destinationFullName , true);
if (destinationFullName == file.FullName) {
logTrace(TraceEventType.Information, "Overwritten file " + file.FullName + " with " + destinationFullName);
}
Is there a good way to detect if a file is being overwritten instead of manually comparing file name of source and destination. I was like to log a message if CopyTo overwrites a file.
If you don't want to check if the file exists before you try to copy, you could use the File.Copy() method where it says right in the documentation that overwriting a file is not allowed:
Copies an existing file to a new file. Overwriting a file of the same name is not allowed.
...
IOException
destFileName exists.
So you could put the Copy in a try, and then catch an IOException that would indicate that the file already exists. See the link I pasted for more information.
I am sure you have a good reason for not wanting to check for the existence of the file in advance. I don't normally recommend using a try catch block like this though.

Issue with deleting a binary file

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.

I get "Process can not access the file...." error while deleting the FILE

I have three folders in my BIN directory.
1) Backlog
2) InProgress
3) Completed
There are TXT files in Backlog folder. I have used below code to copy files from "Backlog" to "InProgress" during some operation.
System.IO.File.Copy(source,target,true);
File succesfully copied to destination folder. now i want to delete the original file from "Backlog". so I have used below code.
System.IO.File.Delete(source);
It thorws exception, "Process can not access the file source..."
I think its issue with Garbage collection and I need to destroy this using "USING" statement. But i tried below, it says syntax for USING is wrong :(
using(System.IO.File.Copy(source,target,true)){}
I have tried below MOVE, but I still get same error.
using(System.IO.File.Move(source,target))
Note: MOVE is success during moving file from FOLDER 1 to FOLDER 2,
MOVE is FAILED during moving file from FOLDER 2 to FOLDER 3,
So I feel, after first MOVE, we have to reset something??
FULL CODE
string filepathBackLog = AppSettings["Backlog"];
string filepathInProgress = AppSettings["InProgress"];
string filepathCompleted = AppSettings["Completed"];
if(!System.IO.File.Exists(filepathBackLog ))
return;
System.IO.File.Move(filepathBackLog ,filepathInProgress ); //Success, I can see it in folder.
System.IO.File.Move(filepathInProgress ,filepathCompleted );//Exception, I think we need to give some time to execute first MOVE.
Kindly guide me how can I resolve this?
Why don't you use File.Move? It will take care of deleting, too.

I can't not seem to successfully overwrite and some other things

So, basically I've created this program and it's copying the selected file to the the company's named folder in the Roaming AppData folder, which isn't so bad. I mean, the setup now isn't so bad but I would like to have more control over it.
string fullFileName = item.FileName;
string fileNameWithExt = Path.GetFileName(fullFileName);
string destPath = Path.Combine(Application.UserAppDataPath, fileNameWithExt);
File.Copy(item.FileName, destPath);
At the beginning of the program it checks to see if the custom AppData folder is there.
public void checkADfolder()
{
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string specificFolder = Path.Combine(folder, ".program");
if (!Directory.Exists(specificFolder))
Directory.CreateDirectory(specificFolder);
}
I want the files to go to the AppData folder .program instead of the folder with the Application company name.
Also, I am running into an issue with this. When a user selects a file, and then closes the program and opens the program again and happens to select the same file, it gives an error because the file already exists. I need to have it overwrite all other files when the same file is selected.
Screw it, I'll also ask this to why I am here.
I need the user selected file to replace another file in the AppData folder and rename the user selected file.
Basically. User selects file. File name is "user.txt". Now it's in Roaming > .program > user.txt
I need that file to replace a file let's say it's called "guest.txt". It's in Roaming > .user > guest.txt
I need to copy and rename "user.txt" to "guest.txt" then replace "guest.txt" in the .user folder.
I hope that explains everything well enough.
I figured I would put everything into one post instead of making multiple.
I've searched but can not seem to find any answers :/
To overwrite the file you simply need to use the method here:
File.Copy Method (String, String, Boolean);
To overwrite your other file, simply call the function again like so:
File.Copy(#".\Roaming\program\user.txt", #".\Roaming\user\guest.txt", true);

Saving file in folder and path in database

I want to save image into a folder and the path of the folder to the database.
I have done this with File.Copy(filepath) command but it is giving me error when a file with the same name already exists there.
Second thing in this command is that I have to provide a filename in it from which it is copying the file. If I am modifying a record and not the image then it is giving error that file source cannot be empty.
I have also tried Picture1.image.save(filename) but I have not found any command to overwrite the existing file.
Please help me by providing a simplest way to do all this.
There's an overload to the File.Copy() method that accepts a bool which will determine whether to overwrite any existing files with the same name.
http://msdn.microsoft.com/en-us/library/9706cfs5.aspx
File.Copy(sourceFileName, destFileName, true) Will force an overwrite of existing file.
Refer MSDN File.Copy
if(File.Exists(destinationFileName))
{
File.Delete(destinationFileName);
}
File.Copy(sourceFileName, destinationFileName);
sourceFileName shoudl be the full path of the source file(including the file name).
destinationFileName should be the fullpath (including the filename) where you want to save the file.
you have to first check whether file exists or not?
using FileInfo,
FileInfo file = new FileInfo(location);
if(file.Exists())
{
File.Delete(location);
File.Copy(srcLocation, location);
}
In this way you can avoid the error.

Categories