Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# multiple instances of program reading from same file

Tags:

c#

file

I wrote a program that reads from file, processes it according to given parameters and writes some output. I was curious, if there can occur any strange problems when user creates more instances of my program (by opening executable file) and runs them over the same file.

I read from file with while loop and file.ReadLine().

like image 551
Perlnika Avatar asked Oct 20 '11 16:10

Perlnika


1 Answers

I was curious, if there can occur any strange problems when user creates more instances of my program (by opening executable file) and runs them over the same file.

The way this is worded leads me to think that you are concerned that the user might accidently run multiple instances of the program against the same file. If that is your concern, then you can prevent problems from this by opening the file in an exclusive mode. The operating system itself will ensure that only the single instance of the program has access to the file for as long as you hold the file open.

If you access the file with a FileStream object, then I believe that exclusive mode is the default, so you don't have to worry about this at all. Just make sure your stream stays open through all the reads and writes for which consistency is required.

If another instance of the program attempts to open the file, then it will throw a IOException and not allow the access. You can either let the program crash, or you can notify the user that the file is already being used and give them the option to choose another file, or whatever.

UPDATE

If you want to read from the same file in many instances of the program, with no instance writing to it, then that is also easily doable. Just open the file in shared read-only mode, and there is no problem at all letting lots of programs read the file simultaneously.

using (Stream stream = new FileStream(filePath, FileMode.Open, 
                                      FileAccess.Read, FileShare.Read))
like image 61
Jeffrey L Whitledge Avatar answered Sep 24 '22 13:09

Jeffrey L Whitledge