简体   繁体   中英

How to remove a file moved with a FileUpLoad [asp.net] C#

I have a process that loads, process and MOVES a file CSV. This behavior has been represented by 2 ways, but I have a problem in the 2nd one described below:

  1. The source and destination directories are set in a database. So read and move the file works excellent disappearing the copy from the source directory. (GOOD)

  2. The source directory has been got from a FileUpload control (fuControl.PostedFile.FileName) and destination is still set in a database. So read and move the file, but at this point, I see that the file is copied into destination directory but a locked copy remains in the source directory and only disappears if I refresh the page (F5) or quit the internet browser. (NOT GOOD) So, How can I avoid this?

Here my sample code:

    private void RunProcess(string path)
    {
        try
        {
            using (StreamReader stream = File.OpenText(path))
            {
                this.ProcessFile(stream);
            }
            string destination = this.GetDestinationPath(); //Get the path from DB
            string fileName = Path.GetFileName(path);
            File.Move(path, destination + fileName);
        }
        catch (Exception e)
        {
            throw new Exception(e.Message, e);
        }
    }

-----EDIT-----

I have my FileUpload control in a repeater and I use it like this. It's not working, a copy is still remaining.

    protected void repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "Browse")
        {
            using (FileUpload fuSource = (FileUpload)e.Item.FindControl("fuSource"))
            {
                if (fuSource != null)
                {
                    if (String.IsNullOrEmpty(fuSource.FileName) == false)
                    {
                        string filePath = fuSource.PostedFile.FileName;
                        this.RunProcess(filePath);
                    }
                }
            }
        }
   }

-----EDIT 2-----

    public void ProcessFile(StreamReader stream)
    {
        string line = String.Empty;
        while ((line = stream.ReadLine()) != null)
        {
            //Just 1 line.
            Console.WriteLine(line);
        }
    }

FileUpload is disposeable and as such it should be wrapped in a using statement. This should release any file locks that would otherwise be held until the web application times out.

using(var fileUploadControl = new FileUpload())//...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM