FileInfo.CopyTo how to detect overwrite - c#

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.

Related

C# - interop excel

I want to filling windows form data to excel. the end of code I give validation so if the filename exist on specific location it would not save it again
string savingNewForm = "C:\\temp\\" + temp;
if (File.Exists(savingNewForm))
{
MessageBox.Show("File already exist!");
oBook.Close();
oApp.Quit();
}
else
{
oBook.SaveAs(savingNewForm);
oBook.Close();
oApp.Quit();
MessageBox.Show("Your file saved");
}
but when user save the same filename it give error.
I think the main problem is on if (File.Exists(savingNewForm)) cause it's not checking if the filename exist or not, instead it goes to else and give a popup excel asking if I want to replace or not.
What is the value of temp? There could be a problem if the filename contains invalid characters or is too long, etc.
From MSDN:
The Exists method should not be used for path validation, this method
merely checks if the file specified in path exists. Passing an invalid
path to Exists returns false.
If path describes a directory, this method returns false.
The Exists method returns false if any error occurs while trying to determine if the specified file exists.
If the directory doesn't exist or if the user does not have permission to read the file (maybe it's locked) then File.Exists() will return false.
If it's an issue with the existence of the file, see Softerware's answer. If you want Excel to not ask the user to overwrite, try:
oApp.DisplayAlerts = false;
Although I haven't worked with your excel library, suggest you to try workaround:
save into another file;
remove target;
move saved file to target filename.
Error on file removing will be more informative anycase.

System.IO.File.Copy never overwrites

In my WinForm I would like to copy/overwrite files.
When the destination file does not exist, the file gets created OK. When the file already exists, it never gets overwriten. Path is on my local computer.
There are no exceptions thrown, and I gave full access to "Everyone". Same issue with FileInfo. Only when I delete the file first it gets created!
My Code:
//File.Delete(path + "gauche.png");
try
{
// FileInfo fi = new FileInfo(Path.Combine(path, Num_Gauche.Value + ".png"));
//fi.CopyTo(Path.Combine(path, "gauche.png"), true);
File.Copy(Path.Combine(path, Num_Gauche.Value + ".png"), Path.Combine(path, "gauche.png"), true);
}
catch (Exception ex )
{
Console.WriteLine(ex.Message);
throw;
}
It could be an ownership issue. If the file was created by another user, your process may not be able to overwrite it. Usually like if the file was created by a installer/MSI that you may have issue to overwrite it by another process.
I will just enable that piece of code to delete the file prior to create it if that works.

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.

File Copy - Keep both files if name conflicts

File.Copy allows simple file copying. When a duplicate file name is encountered, File.Copy has a third parameter to determine if the original file is overwritten or not.
Is there a built-in .Net function that allows a third option to rename the copied file and hence keep both files?. For example, the file copy would automatically rename "readme.txt" to "readme - Copy.txt" if another readme.txt already existed in the destination folder - similar to Windows Explorer functionality?
I realize it can be written but didn't want reinvent the wheel if it exists.
Thanks in advance.
Nope, this functionality doesn't exist out of the box (thankfully, as it would introduce a responsibility to the framework which it ought not to have*,) so if you want this, then you will need to implement a bespoke solution.
*Which implementation should it take? Appending "- Copy", appending "(n)"? It becomes problematic rather sherpish.
There's nothing you can do all-in-one go with File.Copy, however you could test if the destination exists and then Move instead.
Move takes two parameters, and you can essentially rename at the same time.
if File.Exists(destinationPath) {
File.Move(source, destinationPathRenamed);
} else {
try {
File.Copy(source, destinationPath);
} catch (IOException ex) {
// destinationPath file already exists
File.Move(source, destinationPathRenamed);
}
}
See Move documentation
EDIT:
Updated code above. #xanatos makes a good point about atomic operation. I made no assumptions about whether there are other processes accessing the file(s).
Note that I haven't added other error handling for the source file being deleted before the operation begins either.
var destinationPath = c:\temp\archive.txt;
if(File.Exists(destinationPath))
destinationPath = string.Format("c:\temp\archive.{0}.txt", DateTime.Now.ToString("yyyyMMddHHmmffff"));
File.Move(filePath, destinationPath );

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