无法读取上传路径中的文件(由其他进程使用)

时间:2016-07-05 11:43:48

标签: c#

我将csv文件上传到项目解决方案中的AppData文件夹,并使用以下代码阅读内容:

carthage update HockeySDK-iOS

但它会抛出using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append)) { var buffer = new byte[fileUpload.InputStream.Length]; fileUpload.InputStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); var reader = new StreamReader(System.IO.File.OpenRead(fs.Name));// I check path and file itself in AppData folder. its ok List<string> listA = new List<string>(); List<string> listB = new List<string>(); while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(';'); } 消息:

  

进程无法访问文件'c:\ path \ App_Data \ o_1amtdiagc18991ndq1c1k1c2v1bama.csv'   因为它正被另一个进程使用。

我无法理解它是如何以及为什么使用它我从原始上传的文件创建了这个文件,并且具有唯一的名称..

1 个答案:

答案 0 :(得分:2)

  

我无法理解它的使用方式和原因

因为你还没有关闭写给它的信息流:

using (var fs = new FileStream(Path.Combine(uploadPath, name), ...)

我建议您编写文件,关闭using语句,以便释放句柄,然后阅读:

string fullName = Path.Combine(uploadPath, name);
using (var fs = ...)
{
    // Code as before, but ideally taking note of the return value
    // of Stream.Read, that you're currently ignoring. Consider
    // using Stream.CopyTo
}
// Now the file will be closed
using (var reader = File.OpenText(fullName))
{
    // Read here
}