天天看点

C# 程序间通信的两种方式 FileShare Enumeration

一  读写txt方式

多个程序同时读写一个txt时,按如下的方式,可避免txt被同时操作的问题。FileStream  fStream = new FileStream(strPath,XXX,FileAccess.ReadWrite,FileShare.ReadWrite)

FileShare Enumeration

Member nameDescription Delete

Allows subsequent deleting of a file.

Inheritable

Makes the file handle inheritable by child processes. This is not directly supported by Win32.

None

Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed.

Read

Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

ReadWrite

Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (by this process or another process) will fail until the file is closed.However, even if this flag is specified, additional permissions might still be needed to access the file.(什么叫做additionnal permissions?下面的代码中为FileShare.ReadWrite,若FileStream的实例没有close,其它进程不能访问txt文件)

Write

Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions might still be needed to access the file.

//write
string txtFullPath = "F:\\Signal\\signal.txt";

FileStream fs = new FileStream(txtFullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sr = new StreamWriter(fs);
sw.WriteLine("Signal is out!");
sw.Close();
fs.Close();
//read
string txtPath1 = "F:\\Result\\result.txt";
FileStream stream = new FileStream(txtPath1, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader read = new StreamReader(stream);
string strRead = read.ReadToEnd();
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);// 将txt置空
stream.Close();
read.Close();
           

二  SendMessage方式

       Demo 下载链接: http://download.csdn.net/download/qq_20161893/10029669

       Demo中实现了两个窗体程序间互发消息

上面的Demo中是通过窗口标题栏的名称获取,通过这种方法,两个程序中的窗口句柄都可以正确获取。但是int processHandle = FindWindow(null, "XXX”) 对于公司的软件却返回0,暂原因不明。

换个思路,先通过程序名得到PID(XXX.exe为XXX,这个地方有个坑,vs调试启动,是XXX.vshost,而不是XXX),而后通过PID获取程序句柄。

using System.Diagnostics;
using System.Runtime.InteropServices;

Process[] localByName = Process.GetProcessesByName("XXX");
IntPtr processHandle1 = localByName[0].MainWindowHandle;
           

最终效果如下:点击发送,另一个程序收到消息后弹出对话框

C# 程序间通信的两种方式 FileShare Enumeration