Reputation: 5311
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:
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. 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);
}
}
Upvotes: 1
Views: 1403
Reputation: 44295
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())//...
Upvotes: 3