首页 > 解决方案 > 进程无法访问该文件,因为它正被另一个进程使用

问题描述

我创建了一个服务工作者,它读取串行端口信息并创建一个 .csv 文件来保存结果。

但是,当我尝试写入文件时,它说该进程无法访问该文件,尽管(据我所知)该文件未打开,由另一个外部进程使用或文件流正在打开(我正在使用 System.IO .File.WriteAllLines())。问题可能是什么?

static string InsturmentFile = $"{Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)}\\TestLogger\\";

public static void StartConnector()
    {
        Directory.CreateDirectory(InsturmentFile);
    }


public static string FullFilePath(this string fileName)
    {
        return $"{InsturmentFile}\\{fileName}";
    }


public static List<string> LoadFile(this string file)
    {
        if (!System.IO.File.Exists(file))
        {
            return new List<string>();
        }

        return System.IO.File.ReadAllLines(file).ToList();
    }

    public static List<InstrumentRawReading> ConvertToInstrumentRawReadingModel(this List<string> lines)
    {
        List<InstrumentRawReading> output = new List<InstrumentRawReading>();


        foreach (string line in lines)
        {
            string[] cols = line.Split(',');
            InstrumentRawReading u = new InstrumentRawReading();
            string spacer = " "; 
            var now = DateTime.Now;
            now = DateTime.Parse(cols[0]);
            foreach (var reading in u.Readings)
            {                                   
                reading.Name = cols[1];
            }
            output.Add(u);
        }


        return output;
    }

public static void SaveReadingsLogToFile(this List<InstrumentRawReading> models, string fileName)
    {
        try
        {
            List<string> lines = new List<string>();

            foreach (InstrumentRawReading u in models)
            {
                foreach (var rd in u.Readings)
                {
                    lines.Add($"{rd.Time},{u.SerNo},{rd.Name},{rd.Rdg},{rd.Units}");
                }

            }
            System.IO.File.WriteAllLines(fileName.FullFilePath(), lines);

        }
        catch (Exception ex)
        {
            Console.WriteLine("SaveReadingsLogToFile: " + ex.Message.ToString());
            throw;
        }

    }

这是我正在使用创建 .csv 文件的完整文件创建类,它正在创建并填充一个读数,但似乎在随后调用该方法时它只是停止工作。

标签: c#.net-core

解决方案


如果错误是,Process cannot access the file because it is being used by another process那么无论您说什么,它都会被另一个进程使用

您可以使用Microsoft 的一个不错的工具Process Explorer,您可以搜索文件的文字,它会告诉您哪个进程锁定了您的文件。

单击Find/Find Handle or DLL..并输入您的文件名


推荐阅读