Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting file after upload

I am trying to upload a file with the FileUpload control. When file is uploaded, I extract information from it and then i want to delete it.

I manage to upload it, save it and get the info from it, but when i try to delete it i get the follwing exception "The process cannot access the file 'D:\IIS**OMITTED***\V75 personal ny.csv' because it is being used by another process.

 string fn = Path.GetFileName(fu.PostedFile.FileName);
        string SaveLocation = Server.MapPath("UploadedCSVFiles") + "\\" + fn;
        FileInfo fi = new FileInfo(SaveLocation);

            fu.PostedFile.SaveAs(SaveLocation);
            fu.PostedFile.InputStream.Dispose();
            DataTable dt = AMethodThatUsesFile(SaveLocation);
            fi.Delete();
like image 292
Daarwin Avatar asked Nov 04 '11 09:11

Daarwin


3 Answers

Try this code to delete file.

            System.IO.File.Delete(SaveLocation );

You specified a method AMethodThatUsesFile(SaveLocation);. If it uses any classes like StreamReader to read file, please close the reader using StreamReader.Close(); method before trying to delete

like image 80
Prasanth Avatar answered Nov 08 '22 23:11

Prasanth


dispose the fi before deleting. and then us File.Delete(). remember to use using statements when use disposable objects, or dispose it after use.

like image 23
Chamika Sandamal Avatar answered Nov 09 '22 00:11

Chamika Sandamal


using System.io

 File.Delete(Server.MapPath("../Nurturing/" + fnevents));
            FileInfo fInfoEvent;
            fInfoEvent = new FileInfo(fnevents);
            fInfoEvent.Delete();

here fnevents is the name of the file that u are deleting. Nurturing is the name of the folder.

like image 1
ketan italiya Avatar answered Nov 08 '22 22:11

ketan italiya