簡體   English   中英

如何刪除使用FileUpLoad移動的文件[asp.net] C#

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

我有一個加載,處理和移動文件CSV的過程。 此行為已由2種方式表示,但我在下面描述的第2種方法中遇到問題:

  1. 源目標和目標目錄在數據庫中設置。 因此讀取和移動文件的工作原理很好,從源目錄中消失了副本。 (好)

  2. 源目錄是從FileUpload控件(fuControl.PostedFile.FileName)獲取的,目標仍在數據庫中設置。 因此,讀取並移動文件,但此時,我看到文件被復制到目標目錄,但鎖定的副本仍保留在源目錄中,只有在刷新頁面(F5)或退出Internet瀏覽器時才會消失。 (不好)那么,我該如何避免這種情況?

這是我的示例代碼:

    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);
        }
    }

- - -編輯 - - -

我在轉發器中有我的FileUpload控件,我就像這樣使用它。 它不起作用,副本仍然存在。

    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);
                    }
                }
            }
        }
   }

-----編輯2 -----

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

FileUpload是可處置的,因此它應該包含在using語句中。 這應該釋放在Web應用程序超時之前保留的任何文件鎖。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM