从同一个文件读入程序的C#多个实例 [英] C# multiple instances of program reading from same file

查看:154
本文介绍了从同一个文件读入程序的C#多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个程序,它从文件读取,根据给定的参数进行处理和写入一些输出。我很好奇,如果当用户(通过打开可执行文件)创建我的程序的多个实例,并运行它们在同一个文件有可能出现的任何奇怪的问题。



我读从while循环和file.ReadLine()文件。



非常感谢你。


解决方案

我很好奇,如果当用户(通过打开可执行文件)创建我的程序的多个实例,并运行它们在同一个文件有可能出现的任何奇怪的问题。




这是措辞方式让我觉得你担心用户可能意外地运行针对同一个文件的程序的多个实例。如果这是你的关心,那么你可以通过在独占模式打开该文件防止此问题。操作系统本身将确保只有该程序的单个实例访问,只要你拿着打开的文件的文件。



如果您访问与文件FileStream对象,那么我相信独占模式是默认的,所以你不必担心这个的。只要确保你的流保持打开状态,通过所有的读取和写入要求其一致性。



如果该程序的另一个实例试图打开该文件,那么它会抛出一个IOException异常,而不是允许访问。您可以让程序崩溃,或者您也可以通知用户已被使用的文件,并让他们选择其他文件,或任何选项。



< STRONG>更新



如果您想从程序的许多实例相同的文件阅读,没有实例,写它,那也很方便可行的。就在共享只读模式打开文件,并没有一点问题都没有,让很多项目同时读取该文件。

 使用(流流=新的FileStream(文件路径,FileMode.Open,
FileAccess.Read,FileShare.Read))


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().

Thank you very much.

解决方案

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))

这篇关于从同一个文件读入程序的C#多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆