This repository was archived by the owner on Mar 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 650
Expand file tree
/
Copy pathNativeFile.cs
More file actions
393 lines (343 loc) · 17.2 KB
/
Copy pathNativeFile.cs
File metadata and controls
393 lines (343 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace SharpDX.IO
{
/// <summary>
/// Windows File Helper.
/// </summary>
public static class NativeFile
{
/// <summary>
/// Checks if the specified file path exists.
/// </summary>
/// <param name="filePath">The file path.</param>
/// <returns><c>true</c> if the specified file path exists, <c>false</c> otherwise</returns>
public static bool Exists(string filePath)
{
try
{
#if !WIN8METRO
var fullPath = Path.GetFullPath(filePath);
#else
var fullPath = filePath;
#endif
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesEx(fullPath, 0, out data))
{
return true;
}
} catch {}
return false;
}
/// <summary>
/// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
/// </summary>
/// <param name="path">The file to open for reading. </param>
/// <returns>A byte array containing the contents of the file.</returns>
public static byte[] ReadAllBytes(string path)
{
byte[] buffer;
using (var stream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read))
{
int offset = 0;
long length = stream.Length;
if (length > 0x7fffffffL)
{
throw new IOException("File too long");
}
int count = (int)length;
buffer = new byte[count];
while (count > 0)
{
int num4 = stream.Read(buffer, offset, count);
if (num4 == 0)
{
throw new EndOfStreamException();
}
offset += num4;
count -= num4;
}
}
return buffer;
}
/// <summary>
/// Opens a text file, reads all lines of the file, and then closes the file.
/// </summary>
/// <param name="path">The file to open for reading. </param>
/// <returns>A string containing all lines of the file.</returns>
public static string ReadAllText(string path)
{
return ReadAllText(path, Encoding.UTF8);
}
/// <summary>
/// Opens a text file, reads all lines of the file, and then closes the file.
/// </summary>
/// <param name="path">The file to open for reading.</param>
/// <param name="encoding">The encoding.</param>
/// <param name="sharing">The sharing.</param>
/// <returns>A string containing all lines of the file.</returns>
public static string ReadAllText(string path, Encoding encoding, NativeFileShare sharing = NativeFileShare.Read)
{
using (var stream = new NativeFileStream(path, NativeFileMode.Open, NativeFileAccess.Read, sharing))
{
using (StreamReader reader = new StreamReader(stream, encoding, true, 0x400))
{
return reader.ReadToEnd();
}
}
}
#if W8CORE
internal struct CREATEFILE2_EXTENDED_PARAMETERS
{
public uint dwSize;
public uint dwFileAttributes;
public uint dwFileFlags;
public uint dwSecurityQosFlags;
public IntPtr lpSecurityAttributes;
public IntPtr hTemplateFile;
};
private enum FILE_INFO_BY_HANDLE_CLASS : int
{
FileBasicInfo = 0,
FileStandardInfo = 1,
FileNameInfo = 2,
FileRenameInfo = 3,
FileDispositionInfo = 4,
FileAllocationInfo = 5,
FileEndOfFileInfo = 6,
FileStreamInfo = 7,
FileCompressionInfo = 8,
FileAttributeTagInfo = 9,
FileIdBothDirectoryInfo = 10, // 0xA
FileIdBothDirectoryRestartInfo = 11, // 0xB
FileIoPriorityHintInfo = 12, // 0xC
FileRemoteProtocolInfo = 13, // 0xD
FileFullDirectoryInfo = 14, // 0xE
FileFullDirectoryRestartInfo = 15, // 0xF
FileStorageInfo = 16, // 0x10
FileAlignmentInfo = 17, // 0x11
MaximumFileInfoByHandlesClass
};
[StructLayout(LayoutKind.Sequential)]
private struct FILE_STANDARD_INFO
{
public long AllocationSize;
public long EndOfFile;
public int NumberOfLinks;
public int DeletePending;
public int Directory;
};
/// <summary>
/// Gets the size of the file.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="fileSize">Size of the file.</param>
/// <returns></returns>
/// <unmanaged>GetFileSizeEx</unmanaged>
internal static bool GetFileSizeEx(IntPtr handle, out long fileSize)
{
FILE_STANDARD_INFO info;
unsafe
{
var result = GetFileInformationByHandleEx(handle, FILE_INFO_BY_HANDLE_CLASS.FileStandardInfo, new IntPtr(&info), Utilities.SizeOf<FILE_STANDARD_INFO>());
fileSize = info.EndOfFile;
return result;
}
}
#endif
[StructLayout(LayoutKind.Sequential)]
internal struct FILETIME
{
public uint DateTimeLow;
public uint DateTimeHigh;
public DateTime ToDateTime()
{
return DateTime.FromFileTimeUtc((((long)DateTimeHigh) << 32) | ((uint)DateTimeLow));
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct WIN32_FILE_ATTRIBUTE_DATA
{
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint FileSizeHigh;
public uint FileSizeLow;
}
/// <summary>
/// Gets the last write time access for the specified path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns>The last write time access</returns>
public static DateTime GetLastWriteTime(string path)
{
WIN32_FILE_ATTRIBUTE_DATA data;
if (GetFileAttributesEx(path, 0, out data))
{
return data.LastWriteTime.ToDateTime().ToLocalTime();
}
return new DateTime(0);
}
#if WP8
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool ReadFileDelegate(IntPtr fileHandle, IntPtr buffer, int numberOfBytesToRead, out int numberOfBytesRead, IntPtr overlapped);
internal static readonly ReadFileDelegate ReadFile;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool FlushFileBuffersDelegate(IntPtr hFile);
internal static readonly FlushFileBuffersDelegate FlushFileBuffers;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool WriteFileDelegate(IntPtr fileHandle, IntPtr buffer, int numberOfBytesToRead, out int numberOfBytesRead, IntPtr overlapped);
internal static readonly WriteFileDelegate WriteFile;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool SetFilePointerExDelegate(IntPtr handle, long distanceToMove, out long distanceToMoveHigh, SeekOrigin seekOrigin);
internal static readonly SetFilePointerExDelegate SetFilePointerEx;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool SetEndOfFileDelegate(IntPtr handle);
internal static readonly SetEndOfFileDelegate SetEndOfFile;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate IntPtr CreateDelegate([MarshalAs(UnmanagedType.LPWStr)] string fileName, NativeFileAccess desiredAccess, NativeFileShare shareMode, NativeFileMode mode, IntPtr extendedParameters);
internal static readonly CreateDelegate Create;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate bool GetFileInformationByHandleExDelegate(IntPtr handle, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, IntPtr lpFileInformation, int dwBufferSize);
private static readonly GetFileInformationByHandleExDelegate GetFileInformationByHandleEx;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
internal delegate bool GetFileAttributesExDelegate([MarshalAs(UnmanagedType.LPWStr)] string name, int fileInfoLevel, out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
internal static readonly GetFileAttributesExDelegate GetFileAttributesEx;
static NativeFile()
{
// Initialize all the DllImports at once, since we are going to use all of them anyway.
ReadFile = (ReadFileDelegate) Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.ReadFile()), typeof (ReadFileDelegate));
FlushFileBuffers = (FlushFileBuffersDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.FlushFileBuffers()), typeof(FlushFileBuffersDelegate));
WriteFile = (WriteFileDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.WriteFile()), typeof(WriteFileDelegate));
SetFilePointerEx = (SetFilePointerExDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.SetFilePointerEx()), typeof(SetFilePointerExDelegate));
SetEndOfFile = (SetEndOfFileDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.SetEndOfFile()), typeof(SetEndOfFileDelegate));
Create = (CreateDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.CreateFile2()), typeof(CreateDelegate));
GetFileInformationByHandleEx = (GetFileInformationByHandleExDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.GetFileInformationByHandleEx()), typeof(GetFileInformationByHandleExDelegate));
GetFileAttributesEx = (GetFileAttributesExDelegate)Marshal.GetDelegateForFunctionPointer(new IntPtr(SharpDX.WP8.Interop.GetFileAttributesExW()), typeof(GetFileAttributesExDelegate));
}
#else
/// <summary>
/// Reads to a file.
/// </summary>
/// <param name="fileHandle">The file handle.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="numberOfBytesToRead">The number of bytes to read.</param>
/// <param name="numberOfBytesRead">The number of bytes read.</param>
/// <param name="overlapped">The overlapped.</param>
/// <returns>A Result</returns>
/// <unmanaged>ReadFile</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "ReadFile", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool ReadFile(IntPtr fileHandle, IntPtr buffer, int numberOfBytesToRead, out int numberOfBytesRead, IntPtr overlapped);
[DllImport("kernel32.dll", EntryPoint = "FlushFileBuffers", SetLastError = true)]
internal static extern bool FlushFileBuffers(IntPtr hFile);
/// <summary>
/// Writes to a file.
/// </summary>
/// <param name="fileHandle">The file handle.</param>
/// <param name="buffer">The buffer.</param>
/// <param name="numberOfBytesToRead">The number of bytes to read.</param>
/// <param name="numberOfBytesRead">The number of bytes read.</param>
/// <param name="overlapped">The overlapped.</param>
/// <returns>A Result</returns>
/// <unmanaged>WriteFile</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "WriteFile", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool WriteFile(IntPtr fileHandle, IntPtr buffer, int numberOfBytesToRead, out int numberOfBytesRead, IntPtr overlapped);
/// <summary>
/// Sets the file pointer.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="distanceToMove">The distance to move.</param>
/// <param name="distanceToMoveHigh">The distance to move high.</param>
/// <param name="seekOrigin">The seek origin.</param>
/// <returns></returns>
/// <unmanaged>SetFilePointerEx</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "SetFilePointerEx", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool SetFilePointerEx(IntPtr handle, long distanceToMove, out long distanceToMoveHigh, SeekOrigin seekOrigin);
/// <summary>
/// Sets the end of file.
/// </summary>
/// <param name="handle">The handle.</param>
/// <returns></returns>
/// <unmanaged>SetEndOfFile</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "SetEndOfFile", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool SetEndOfFile(IntPtr handle);
[DllImport("kernel32.dll", EntryPoint="GetFileAttributesExW", CharSet = CharSet.Unicode, SetLastError = true)]
internal static extern bool GetFileAttributesEx(string name, int fileInfoLevel, out WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
#if W8CORE
/// <summary>
/// Creates the specified lp file name.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="desiredAccess">The desired access.</param>
/// <param name="shareMode">The share mode.</param>
/// <param name="mode">The creation disposition.</param>
/// <param name="extendedParameters">The extended parameters.</param>
/// <returns>A handle to the created file. IntPtr.Zero if failed.</returns>
/// <unmanaged>CreateFile2</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern IntPtr Create(
string fileName,
NativeFileAccess desiredAccess,
NativeFileShare shareMode,
NativeFileMode mode,
IntPtr extendedParameters);
[DllImport("kernel32.dll", EntryPoint = "GetFileInformationByHandleEx", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern bool GetFileInformationByHandleEx(IntPtr handle, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, IntPtr lpFileInformation, int dwBufferSize);
#else
/// <summary>
/// Creates the file.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="desiredAccess">The desired access.</param>
/// <param name="shareMode">The share mode.</param>
/// <param name="securityAttributes">The security attributes.</param>
/// <param name="mode">The creation disposition.</param>
/// <param name="flagsAndOptions">The flags and attributes.</param>
/// <param name="templateFile">The template file.</param>
/// <returns>A handle to the created file. IntPtr.Zero if failed.</returns>
/// <unmanaged>CreateFile</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "CreateFile", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern IntPtr Create(
string fileName,
NativeFileAccess desiredAccess,
NativeFileShare shareMode,
IntPtr securityAttributes,
NativeFileMode mode,
NativeFileOptions flagsAndOptions,
IntPtr templateFile);
/// <summary>
/// Gets the size of the file.
/// </summary>
/// <param name="handle">The handle.</param>
/// <param name="fileSize">Size of the file.</param>
/// <returns></returns>
/// <unmanaged>GetFileSizeEx</unmanaged>
[DllImport("kernel32.dll", EntryPoint = "GetFileSizeEx", SetLastError = true, CharSet = CharSet.Ansi)]
internal static extern bool GetFileSizeEx(IntPtr handle, out long fileSize);
#endif
#endif
// END WP8
}
}