c# - 进程无法访问该文件,因为它正被另一个进程使用
问题描述
我创建了一个服务工作者,它读取串行端口信息并创建一个 .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 文件的完整文件创建类,它正在创建并填充一个读数,但似乎在随后调用该方法时它只是停止工作。
解决方案
如果错误是,Process cannot access the file because it is being used by another process
那么无论您说什么,它都会被另一个进程使用。
您可以使用Microsoft 的一个不错的工具Process Explorer,您可以搜索文件的文字,它会告诉您哪个进程锁定了您的文件。
单击Find
/Find Handle or DLL..
并输入您的文件名
推荐阅读
- node.js - 完成安装后 IPFS 无法在浏览器上运行
- vim - 在 Vim 中,如何设置在插件加载后运行的自动命令?
- javascript - 如何在 if 语句中使用按钮值和对象值来检查正确答案(进行测验)
- javascript - 如何在每次使用 jQuery 或 javascript 的下午 6:30 之后在 datepicker 中禁用今天的日期
- python - 如何使用正则表达式和精确文字匹配的组合来获取索引值
- popup - 如何在弹出窗口中显示最新数据
- firebase - Flutter_facebook_plugin 上的问题
- java - 为什么@Table注释在通过spring的CRUD操作中是可选的
- java - Jersey ApplicationPath 不工作 - 404 错误
- google-apps-script - 从第 N 列获取最后一行单元格值,如果匹配特定单词发送电子邮件