public static FileStream Open(string filepath, FileMode mode)
{
//opened in the specified mode and path, with read/write access and not shared
FileStream fs = null;
uint umode = GetMode(mode);
uint uaccess = GENERIC_READ | GENERIC_WRITE;
uint ushare = 0; //not shared
if (mode == FileMode.Append)
uaccess = FILE_APPEND_DATA;
SafeFileHandle sh = CreateFileW(LongFileName(filepath), uaccess, ushare, IntPtr.Zero, umode, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
int iError = Marshal.GetLastWin32Error();
if (/*(iError > 0 && !(mode == FileMode.Append && iError == ERROR_ALREADY_EXISTS)) || */sh.IsInvalid)
{
throw new Exception("Error opening file Win32 Error:" + iError);
}
else
{
fs = new FileStream(sh, FileAccess.ReadWrite);
}
// if opened in append mode
if (mode == FileMode.Append)
{
if (!sh.IsInvalid)
{
SetFilePointer(sh, 0, IntPtr.Zero, FILE_END);
}
}
return fs;
}