teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

回答でいただいたURLを参考に修正したプログラムを掲載

2019/07/09 08:47

投稿

nobureon2
nobureon2

スコア21

title CHANGED
File without changes
body CHANGED
@@ -107,4 +107,64 @@
107
107
  throw ex;
108
108
  }
109
109
  }
110
+ ```
111
+
112
+ ```C#
113
+ // 下記URLを参考に修正
114
+ // https://www.atmarkit.co.jp/bbs/phpBB/viewtopic.php?topic=16274&forum=7
115
+
116
+ public void WriteMailSlot(string slot, string message)
117
+ {
118
+ System.IntPtr hNmPipe = IntPtr.Zero; // 名前付きパイプハンドル
119
+
120
+ //セキュリティ記述子作成
121
+ SECURITY_DESCRIPTOR sd = new SECURITY_DESCRIPTOR();
122
+ bool bTemp = InitializeSecurityDescriptor(ref sd, 1);
123
+ bool bTemp2 = SetSecurityDescriptorDacl(ref sd, 1, IntPtr.Zero, 0);
124
+ GCHandle sdHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);
125
+
126
+ try
127
+ {
128
+ SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
129
+ sa.nLength = Marshal.SizeOf(sa);
130
+ sa.lpSecurityDescriptor = sdHandle.AddrOfPinnedObject();
131
+ sa.bInheritHandle = 0;
132
+
133
+ //メールスロットを開く
134
+ SafeFileHandle fileHandle = CreateFile(slot,
135
+ DesiredAccess.GENERIC_READ | DesiredAccess.GENERIC_WRITE,
136
+ ShareMode.FILE_SHARE_READ | ShareMode.FILE_SHARE_WRITE,
137
+ ref sa,
138
+ CreationDisposition.OPEN_EXISTING,
139
+ FlagsAndAttributes.FILE_ATTRIBUTE_NORMAL,
140
+ (IntPtr)0);
141
+
142
+ if (fileHandle.IsInvalid)
143
+ {
144
+ int errCode = Marshal.GetLastWin32Error();
145
+ MessageBox.Show("Win32エラー・コード:" +
146
+ String.Format("{0:X8}", errCode));
147
+ }
148
+
149
+
150
+ // 指定の文字列を出力する
151
+ using (FileStream fs = new FileStream(fileHandle, FileAccess.Write))
152
+ {
153
+ byte[] msg = Encoding.UTF8.GetBytes(message);
154
+ fs.Write(msg, 0, msg.Length);
155
+ }
156
+
157
+ }
158
+ catch (Exception ex)
159
+ {
160
+ System.Diagnostics.Debug.WriteLine(ex.Message);
161
+ System.Diagnostics.Debug.WriteLine(ex.StackTrace);
162
+ throw ex;
163
+ }
164
+ finally
165
+ {
166
+ sdHandle.Free();
167
+ }
168
+ }
169
+
110
170
  ```