[英]How to remove a file moved with a FileUpLoad [asp.net] C#
I have a process that loads, process and MOVES a file CSV. 我有一个加载,处理和移动文件CSV的过程。 This behavior has been represented by 2 ways, but I have a problem in the 2nd one described below: 此行为已由2种方式表示,但我在下面描述的第2种方法中遇到问题:
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) (好)
The source directory has been got from a FileUpload control (fuControl.PostedFile.FileName) and destination is still set in a database. 源目录是从FileUpload控件(fuControl.PostedFile.FileName)获取的,目标仍在数据库中设置。 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. 因此,读取并移动文件,但此时,我看到文件被复制到目标目录,但锁定的副本仍保留在源目录中,只有在刷新页面(F5)或退出Internet浏览器时才会消失。 (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. 我在转发器中有我的FileUpload控件,我就像这样使用它。 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----- -----编辑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. FileUpload是可处置的,因此它应该包含在using语句中。 This should release any file locks that would otherwise be held until the web application times out. 这应该释放在Web应用程序超时之前保留的任何文件锁。
using(var fileUploadControl = new FileUpload())//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.