C# Can';无法绕过IOException错误:无法访问该文件

C# Can';无法绕过IOException错误:无法访问该文件,c#,ioexception,system.io.fileinfo,C#,Ioexception,System.io.fileinfo,我很难找出这个例外。直到大约两个月前,这种方法一直工作得完美无缺。我对它所做的唯一更改是将解析后的文件移动到另一个文件夹,这个文件夹也工作了一段时间。现在,每次自定义Windows Filewatcher服务访问此方法时,我都会收到以下错误消息: There was an Input Output file error: System.IO.IOException: The process cannot access the file '\\mkfiler01\ops\Envcom\EXEC\E

我很难找出这个例外。直到大约两个月前,这种方法一直工作得完美无缺。我对它所做的唯一更改是将解析后的文件移动到另一个文件夹,这个文件夹也工作了一段时间。现在,每次自定义Windows Filewatcher服务访问此方法时,我都会收到以下错误消息:

There was an Input Output file error: System.IO.IOException: The process cannot access the file '\\mkfiler01\ops\Envcom\EXEC\ENVCOM\Lab\COD\Exports\DataLog\DL_DR6000_1601329_2017-Jan-10_12_15_01.csv' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding)
   at System.IO.File.ReadLines(String path)
   at COD_Automation.COD_AUTO.ParseData(String filePath)

我不知道它可能是什么过程,因为它在写入日志后一开始就出现了问题。我们的仪器创建.csv文件并将其发送到正在监视的网络文件夹位置。然后启动服务。解析是服务中发生的第一件事。如果能在这方面得到任何帮助,我将不胜感激

以下是解析方法的代码:

public void ParseData(String filePath)
    {
        Write2LogFile("The parsing of " + filePath + " has begun.");

        //Create a dictionary collections with int keys (rowNums) and String values (each line of Strings)
        Dictionary<int, String> eachCSVLine = new Dictionary<int, string>();

        //String array that holds the contents of the specified row
        String[] lineContent;

        int rowNum = 1;
        try
        {
            /*loop through each line of the csv file, add it the collection
            *and iterate the row number*/
            foreach (string line in File.ReadLines(filePath))
            {
                eachCSVLine.Add(rowNum, line);
                rowNum++;
            }

            //Get the required line and split it by "," into an array
            if (eachCSVLine.ContainsKey(5))
            {
                String reqLine = eachCSVLine[5];
                lineContent = reqLine.Split(',');
            }
            else
            {
                String reqLine = eachCSVLine[4];
                lineContent = reqLine.Split(',');
            }

            /*Get the required values(index 2 for parsed Operator ID, index 3 for parsed Sample Number, 
             * index 11 for Sample Result, index 8 for provided Dilution)*/
            AnalysisInitials = lineContent.GetValue(2).ToString();
            SampNum = lineContent.GetValue(3).ToString();      //sample number            

            String result = lineContent.GetValue(11).ToString();
            String dilute = lineContent.GetValue(8).ToString();
            Dilution = Double.Parse(dilute);
            SampResult = Int32.Parse(result);    //sample result

            Write2LogFile("The following result data from " + filePath + " was just parsed: " + AnalysisInitials + "," +
                SampNum + "," + Dilution.ToString() + "," + SampResult.ToString());

            //move the parsed file to the parsed folder
            //File.Move(filePath, parsedPath);
            //Write2LogFile("The following file has been moved to the parsed folder: " + filePath);
        }
        catch (KeyNotFoundException ke)
        {

            Write2LogFile("The data elements could not be accessed from the collection because of the following: " +
                ke.GetBaseException());
            SendMail("The data elements could not be accessed from the collection because of the following: " + ke.GetBaseException());
        }
        catch (ArgumentNullException an)
        {

            Write2LogFile("The was a problem with looping through the " + filePath + " because of the following: " +
                an.GetBaseException());
            SendMail("The was a problem with looping through the " + filePath + " because of the following: " +
                an.GetBaseException());
        }
        catch (ArgumentException ae)
        {

            Write2LogFile("There was a problem with looping through the " + filePath + " because of the following: " +
                ae.GetBaseException());
            SendMail("There was a problem with looping through the " + filePath + " because of the following: " +
                ae.GetBaseException());
        }
        catch (InvalidCastException ce)
        {

            Write2LogFile("The value could not be casted or converted because of the following: " +
                ce.GetBaseException());
            SendMail("The value could not be casted or converted because of the following: " +
                ce.GetBaseException());
        }
        catch (IOException ie)
        {

            Write2LogFile("There was an Input Output file error: " +
                ie.GetBaseException());
            SendMail("There was an Input Output file error: " +
                ie.GetBaseException());
        }

    }
public void ParseData(字符串文件路径)
{
Write2LogFile(“已开始解析“+filePath+”);
//使用int键(rownum)和字符串值(每行字符串)创建字典集合
字典eachCSVLine=新字典();
//包含指定行内容的字符串数组
字符串[]行内容;
int rowNum=1;
尝试
{
/*循环浏览csv文件的每一行,将其添加到集合中
*并迭代行号*/
foreach(File.ReadLines(filePath)中的字符串行)
{
eachCSVLine.Add(rowNum,line);
rowNum++;
}
//获取所需的行并按“,”将其拆分为一个数组
if(每一个容器(5))
{
字符串reqLine=eachCSVLine[5];
lineContent=reqLine.Split(',');
}
其他的
{
字符串reqLine=eachCSVLine[4];
lineContent=reqLine.Split(',');
}
/*获取所需的值(索引2表示已解析的运算符ID,索引3表示已解析的样本号,
*指数11表示样品结果,指数8表示提供的稀释度)*/
AnalysisInitials=lineContent.GetValue(2.ToString();
SampNum=lineContent.GetValue(3).ToString();//样本号
字符串结果=lineContent.GetValue(11).ToString();
字符串稀释=lineContent.GetValue(8.ToString();
稀释=双倍。解析(稀释);
SampResult=Int32.Parse(result);//示例结果
Write2LogFile(“刚刚解析了“+filePath+”中的以下结果数据:“+AnalysisInitials+”,”+
SampNum+“,“+稀释.ToString()+”,“+SampResult.ToString());
//将已解析的文件移动到已解析的文件夹
//Move(filePath,parsedPath);
//Write2LogFile(“以下文件已移动到解析文件夹:“+filePath”);
}
catch(keynotfound异常)
{
Write2LogFile(“由于以下原因,无法从集合访问数据元素:”+
ke.GetBaseException());
SendMail(“由于以下原因,无法从集合访问数据元素:“+ke.GetBaseException());
}
捕获(异常)
{
Write2LogFile(“在“+filePath+”中循环出现问题,原因如下:”+
一个.GetBaseException());
SendMail(“在“+文件路径+”中循环时出现问题,原因如下:”+
一个.GetBaseException());
}
捕获(异常ae)
{
Write2LogFile(“循环通过“+filePath+”时出现问题,原因如下:”+
ae.GetBaseException());
SendMail(“在“+文件路径+”中循环出现问题,原因如下:”+
ae.GetBaseException());
}
捕获(无效卡斯特例外ce)
{
Write2LogFile(“由于以下原因,无法转换或转换该值:”+
GetBaseException());
SendMail(“由于以下原因,无法转换或转换该值:”+
GetBaseException());
}
捕获(IOIE)
{
Write2LogFile(“出现输入输出文件错误:”+
即GetBaseException());
SendMail(“出现输入输出文件错误:”+
即GetBaseException());
}
}

我认为大师为您的问题提供了一个极好的答案:

从这里开始备份:


这是ReadLines()实现中的一个已知错误…

谢谢Quantic。我确实修改了代码,将Using语句(我通常使用)和Filestream包含在内。它现在起作用了。我仍在测试该服务,但我将下面的代码部分更改为下面的代码

旧代码:

/*loop through each line of the csv file, add it the collection
        *and iterate the row number*/
        foreach (string line in File.ReadLines(filePath))
        {
            eachCSVLine.Add(rowNum, line);
            rowNum++;
        }
新代码:

/*loop through each line of the csv file, add it the collection
            *and iterate the row number*/
            using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    string currentLine;
                    while ((currentLine = reader.ReadLine()) != null)
                    {
                        eachCSVLine.Add(rowNum, currentLine);
                        rowNum++;
                    }
                }
            }

这个解决方案是有道理的。这只是为了我的生活,我不知道什么进程甚至可以控制文件在这一点上,为什么工作之前没有这些问题。然而,这是可行的。再次感谢您的输入。

是否仍在写入文件或其他内容?请参阅“我们的仪器创建.csv文件并将其发送到正在监视的网络文件夹位置”--您确定仪器正在释放该文件吗?而且,它位于网络共享上,这意味着任何具有访问权限的用户都可以打开它并将其锁定。您应该尝试将
FileStream
FileMode.Open、FileAccess.Read、FileShare.ReadWrite一起使用,这样即使另一个进程打开了它,您也可以读取它(注意,如果您正在读取,而另一个进程正在写入)作为一个供参考的工具,我使用sysinterals
handle
cli工具来调试这类东西,v非常有用(刚刚使用过)