进程无法访问该文件,因为它正在被另一个进程使用

本文关键字:进程 另一个 因为 访问 文件 | 更新日期: 2023-09-27 18:12:30

我需要上传一个CSV文件到ASP。. NET应用程序,在Azure服务器上。虽然它在我的本地机器上运行良好,但当将其上传到服务器时,会抛出以下错误:

"进程无法访问文件。"C:'inetpub'wwwroot'ImportFiles'9_11.csv",因为它正在被另一个进程"

我代码:

        string fileName = DateTime.Now.ToString().Replace(':', '_').Replace('/', '_').Replace(' ', '_') + Convert.ToString((new Random()).Next(0, 999) * (new Random()).Next(0, 999));
        string path = Server.MapPath("ImportFiles") + "''" + fileName + "" + FileImport.FileName.Substring(FileImport.FileName.IndexOf('.'));
        FileImport.SaveAs(path);
        string pathforSeconStream = path;
        try
        {
            Response.Write("<script> alert('In Try Block');</script>");
            bool flag = true;
            int visiblemessageCount = 0;
            int rollNo = 1;
            StreamReader ColLine = new StreamReader(path);
            string ColInputline = ColLine.ReadLine();
            String[] ColsInput = ColInputline.Split(',');
            ColLine.Close();
            ColLine.Dispose();
            string preFix = "", RollNumber = "";
            StreamReader sr = new StreamReader(pathforSeconStream);
}
catch(Exception ex)
{
}   

进程无法访问该文件,因为它正在被另一个进程使用

生成唯一文件名的代码错误。使用Path.GetTempFileName。

PS永远不会产生异常。请删除catch (Exception ex) {};

修订

而不是FileImport.Save(...)只是保存请求在MemoryStream,然后在它的工作