C# - interop excel - c#

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.

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.

Search for file, if not there then download

How would I search for a file (in the current directory the exe is running in) and if it is not found, it will download it?
I already know how to do the downloading part, WebClient.DownloadFile("link.com","link.exe");
TL;DR:
How would I search for a file in the directory (link.exe) and if it is not there, download it?
If you already have the full path where the file should be located, you can simply call System.IO.File.Exists(thePath), which will return either true or false.
Note that thePath must be the full path to the file, not to the folder.
Or do you need something else?
You want to firstly find out which directory you are in. Then you want check whether the file exsist or not.
string file_location = Environment.CurrentDirectory + "link.exe";
if (File.Exists(file_location) == false)
{
WebClient.DownloadFile("link.com", "link.exe");
}
Environment.CurrentDirectory:
https://msdn.microsoft.com/en-us/library/system.environment.currentdirectory(v=vs.110).aspx
File.Exists:
https://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx

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.

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.

FileUpload - Verifying that an actual file was uploaded

I have a FileUpload control (FileUpload1) on my web form, as well as a "Sumbit" button, a label, and a hidden field that contains a UserID. I have the following code in the button's click event:
string path = Server.MapPath("~/userfiles/");
if (FileUpload.HasFile)
{
try
{
FileUpload1.SaveAs(path + UserID.Value + "/image.jpg");
}
catch
{
Label1.Text = "* unable to upload file";
Label1.Visible = true;
}
}
It works great if I upload an actual file. However, if I type a non-existent filename (for example, "c:\a.jpg", which does not exist on my computer) into the FileUpload's textbox, and click the Sumbit button, HasFile still returns true. Furthermore, SaveAs() does not throw any exceptions, and it is a void function that returns no value indicating success or failure. How do I tell whether a file was actually uploaded?
Just check to see if it exists.
if(File.Exists(myFile)){
//it was uploaded.
}
You could check FileUpload.PostedFile.ContentLength property
You could check if the file exists using File.Exists before calling SaveAs.
Hmmm....
Not sure I understand. First, in your code, FileUpload.HasFile won't compile. If should be FileUpload1.HasFile.
When I correct this, and run your code, this line returns false if the file does not exist...
You can check if file exists after uploading using File.Exists(path); The file object is part of System.IO.
This is not about your actual question, but you should validate any user input, especially if you want users to upload files to a virtual folder on your webserver. You should at least check whether the content type of the file is the one you expect, or - even better, filter (resize) the image using the classes available in the .NET framework.
If you don't do so users may share arbitrary content via your site or place malicious files (e.g. images containing script which might get executed by certain web browsers) on your server.
With additional validation you will also be able to validate if there has actually been content sent.
AND: A really severe vulnerability opens up when you build the save path by concatenating input from a form field (I assume UserID.Value is the POST parameter you mention?). This allows users to decide where to store the content on your server, and, even worse, be able to overwrite existing files!!!

Categories