StreamReader C# error: process cannot access the file because it is being used

StreamReader C# error: process cannot access the file because it is being used

所以我在尝试读取文件时遇到了这个问题。

我正在从一个目录中获取文件名,然后遍历它们以将它们插入到数据库中。但我一直收到错误。当我尝试 Streamread 文件时无法访问文件。

这是我的所有代码,这是唯一真正与该目录一起工作的代码,因此没有其他进程可以锁定该文件。

我一直在这一行收到错误 "using (var reader = new StreamReader(localPath))" 说 "The process cannot access the file 'filename' because it is being used by another process"

public async Task<ResponseBase> GetCsvAsync()
    {
        var response = new ResponseBase();
        try
        {
            DirectoryInfo d = new DirectoryInfo(HostingEnvironment.MapPath($"~/App_Data/IosStats/ToProcess"));//Assuming Test is your Folder
            //FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
            FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
            var filenames = new List<string>();
            foreach (var file in Files)
            {
                filenames.Add(file.Name);
            }

            foreach (var filename in filenames)
            {
                var localPath = HostingEnvironment.MapPath($"~/App_Data/IosStats/ToProcess/{filename}");
                localPath = localPath ?? Path.GetFileName(filename);
                var outputFile = System.IO.File.OpenWrite(localPath);

                using (var reader = new StreamReader(localPath))
                //using (var reader = new StreamReader($"{d}/{file.Name}"))
                {
                    var counter = 0;
                    var columnName = "";
                    while (!reader.EndOfStream)
                    {
                        counter = counter + 1;
                        var line = reader.ReadLine();
                        var values = line.Split(',');
                        var currentRow = new AppDownload();
                        var currentAppHistory = DbContext.AppDownloads.Where(x => x.Platform == AppPlatform.IOS).ToList();
                        if (counter == 5)
                        {
                            columnName = values[1];
                        }

                        if (counter <= 4 & columnName != "")
                        {
                            var csvDate = Convert.ToDateTime(values[0]);
                            var isAlreadyLogged = currentAppHistory.Where(x => x.CsvDate == csvDate).ToList();
                            var currentReplacementRow = new AppDownload();
                            if (isAlreadyLogged.Count == 0)
                            {
                                currentRow.CsvDate = Convert.ToDateTime(values[0]);
                                currentRow.PackageName = "Dialdirect Insurance";
                                currentRow.Platform = AppPlatform.IOS;
                                currentRow.InsertedTime = DateTimeOffset.Now;
                                switch (columnName)
                                {
                                    case "Active Devices":
                                        currentRow.ActiveDeviceInstalls = Convert.ToInt16(values[1]);
                                        break;

                                    case "Installations":
                                        currentRow.DailyDeviceInstalls = Convert.ToInt16(values[1]);
                                        break;

                                    default:
                                        columnName = "";
                                        break;
                                }

                                DbContext.AppDownloads.Add(currentRow);
                            }
                            else
                            {
                                currentReplacementRow = isAlreadyLogged.FirstOrDefault(x => x.CsvDate == csvDate);
                                switch (columnName)
                                {
                                    case "Active Devices":
                                        currentReplacementRow.ActiveDeviceInstalls = Convert.ToInt16(values[1]);
                                        break;

                                    case "Installations":
                                        currentReplacementRow.DailyDeviceInstalls = Convert.ToInt16(values[1]);
                                        break;

                                    default:
                                        columnName = "";
                                        break;
                                }

                                DbContext.AppDownloads.Add(currentReplacementRow);
                            }
                            await DbContext.SaveChangesAsync();
                            var sourceFile = localPath;
                            var destinationFile = HostingEnvironment.MapPath($"~/App_Data/IosStats/Processed/{filename}");
                            System.IO.File.Move(localPath, destinationFile);
                        }
                    }
                }
            }
            response.Success = true;
            return response;
        }
        catch (Exception ex)
        {
            ex.ToExceptionless().Submit();
            response.Success = false;
            return response;
            throw;
        }

    }

我正在拔头发,因为它不想读取文件。任何帮助将不胜感激

您没有关闭 outputFile 流,您似乎也根本没有使用它。

下面的另一个问题是这一行:

System.IO.File.Move(localPath, destinationFile);

您正在移动文件,同时通过 StreamReader 打开文件。

如果在解决@Magnus 提出的问题后,请检查目录权限,看看您是否有写入权限。如果有,请检查是否有任何通过防病毒软件强制执行的组策略。如果在该文件夹中没有与编辑该文件相关的特定策略,请检查是否对文件类型有任何限制。希望这能解决您的问题。