Не удается обойти ошибку IOException: невозможно получить доступ к файлу

Мне трудно понять это исключение IOException. Примерно два месяца назад этот метод работал безупречно. Единственное изменение, которое я внес в него, - это перемещение проанализированного файла в другую папку, что также некоторое время работало. Теперь каждый раз, когда пользовательская служба 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());
        }

    }

person Obie_One    schedule 11.01.2017    source источник
comment
Возможно ли, что файл все еще записывается или что-то в этом роде? См. Этот SO   -  person RamblinRose    schedule 12.01.2017
comment
Наш инструмент создает файл .csv и отправляет его в наблюдаемую сетевую папку. Вы уверены, что инструмент выпускает файл? Также, если он находится в общем сетевом ресурсе, любой пользователь, имеющий доступ, может открыть его, что заблокирует его. Вам следует попробовать код здесь, в котором вы используйте FileStream с FileMode.Open, FileAccess.Read, FileShare.ReadWrite, что должно позволить вам читать его, даже если он открыт другим процессом (будьте осторожны, если вы читаете в то время как другой процесс пишет).   -  person Quantic    schedule 12.01.2017
comment
в качестве fyi - я использую инструмент sysinterals handle cli для отладки такого рода вещей, v полезно (просто использовал его 5 минут назад)   -  person pm100    schedule 12.01.2017


Ответы (2)


Я думаю, что здесь есть отличный ответ на вашу проблему от мастера:

https://stackoverflow.com/a/39142959/4619012

и сделайте резервную копию отсюда:

https://stackoverflow.com/a/39143086/4619012

Это известная ошибка в реализации ReadLines () ...

person Steve Padmore    schedule 11.01.2017

Спасибо, 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++;
                    }
                }
            }

Решение имеет смысл. Просто ради жизни я не мог понять, какой процесс будет иметь контроль над файлом в этот момент и почему раньше работал без этих проблем. Тем не менее, это работает. Еще раз спасибо за вклад.

person Obie_One    schedule 15.01.2017