0

I want to read a file created by a VBA-script in Excel and continually edited by this tool with my C#-program (it opens the file every 5 seconds and reads the data). Unfortunately, as soon as I open my program to read from the file, Excel / my VBA-script is unable to write to the file anymore ("access denied").

This is my C#-Code:

    System.IO.FileStream fs = new System.IO.FileStream("file.txt", 
                                                        System.IO.FileMode.Open, 
                                                        System.IO.FileAccess.Read, 
                                                        System.IO.FileShare.ReadWrite);
    System.IO.StreamReader File = new System.IO.StreamReader(fs);
    // read lines from Stream
    File.Close();

Is there any possibility to continue writing to the file although it is opened in the C#-tool? I already tried copying the file before opening but I get the same error message.

msu-welle
  • 65
  • 1
  • 11
  • You could try making a copy of the file for you to work with. – cbr Mar 16 '16 at 15:31
  • 2
    There's a similar question here with lots of good responses: http://stackoverflow.com/questions/3448230/how-can-i-read-a-text-file-without-locking-it – NickT Mar 16 '16 at 15:31
  • "I already tried copying the file before opening but I get the same error message." ´System.IO.File.Copy("file.txt", "fileCOPY.txt", true);´ did not work either. – msu-welle Mar 16 '16 at 15:33
  • 1
    @NickT Unfortunately those answers only suggest him to use the `FileShare.ReadWrite` flag, which he is already using. – cbr Mar 16 '16 at 15:33
  • How are you reading the text from the stream? – cbr Mar 16 '16 at 15:34
  • @cubrr: I'm using the `StreamReader.ReadLine()` -method in a while-loop to read the text – msu-welle Mar 16 '16 at 15:37
  • how is your vba / excel writing ? – Boo Mar 16 '16 at 15:39
  • @Boo: `Open "FilePath" For Output As #1` and then `Print #1, (Worksheets("Name").Range("A" & i).Value & "...")` The `Print` statement is used inside a Loop to write several lines to the file. The error occurs - according to the debugger - in the line with the `Open` statement – msu-welle Mar 16 '16 at 15:44
  • I've used `File.ReadAllText` for quick reads before, you can try catching the exception and waiting a short time for the other app to close, then trying again. It's a little wasteful. – NickT Mar 16 '16 at 16:09
  • After setting the file to "Shared" in the VB-Script and finding a bug in a different place in my script which caused the program to open the file twice, it works now. Thanks a lot for your help :) – msu-welle Mar 16 '16 at 18:06

0 Answers0