0

I am having a hard time trying to figure out this IOException. This method used to work flawless until about two months ago. The only change I have made to it was moving the parsed file to another folder, which also worked for awhile. Now every time the custom Windows Filewatcher Service gets to this method, I get the following error message:

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)

I can't figure out what process it could be because it craps out at the beginning right after it writes to the log. Our instrument creates the .csv file and sends it to the network folder location that is being watched. Then the service is initiated. The parsing is the first thing that happens in the service. I would appreciate any help on this.

Here is the code for the Parsing Method:

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());
        }

    }
Obie_One
  • 81
  • 10
  • Is it possible the file is still being written to or something? See this [SO](http://stackoverflow.com/questions/699538/file-access-error-with-filesystemwatcher-when-multiple-files-are-added-to-a-dire) – RamblinRose Jan 11 '17 at 21:27
  • 1
    "Our instrument creates the .csv file and sends it to the network folder location that is being watched" -- are you sure the instrument is releasing the file? Also it being on a network share means any user with access could open it which would lock it. You should try [the code here](http://stackoverflow.com/questions/3709104/how-do-you-read-a-file-which-is-in-use) where you use a `FileStream` with `FileMode.Open, FileAccess.Read, FileShare.ReadWrite` which should allow you to read it even if it's open by another process (beware if you are reading *while* the other process is writing though). – Quantic Jan 11 '17 at 21:27
  • as an fyi - i use sysinterals `handle` cli tool to debug this kind of thing, v useful (just used it 5 mins ago) – pm100 Jan 11 '17 at 23:35

2 Answers2

0

I think there is an excellent answer to your issue here from a master:

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

and backup from here:

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

It is a known bug within the ReadLines() implementation...

Community
  • 1
  • 1
Steve Padmore
  • 1,710
  • 1
  • 12
  • 18
0

Thanks Quantic. I did change my code to include Using statements (which I normally use) and Filestream. It works for now. I'm still testing the service but I changed the portion of the code below to the code below it.

Old code:

/*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++;
        }

New code:

/*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++;
                    }
                }
            }

The solution makes sense. It's just for the life of me I could not see what process would even have control over the file at that point and why work before without those problems. Nevertheless, this works. Thanks again for the inputs.

Obie_One
  • 81
  • 10