public int CreateFile(string filename, FileAccess access, FileShare share, FileMode mode, FileOptions options, DokanFileInfo info)
        {
            Trace.WriteLine(string.Format("CreateFile FILENAME({0}) ACCESS({1}) SHARE({2}) MODE({3})", filename, access, share, mode));

            if (mode == FileMode.Create || mode == FileMode.OpenOrCreate || mode == FileMode.CreateNew)
            {
                // we want to write a file
                var fileRef = Extensions.GetFileReference(root, filename.ToFileString());
                fileRef.Create(0);
                return 0;
            }

            if (share == FileShare.Delete)
            {
                return DeleteFile(filename, info);
            }

            if (GetFileInformation(filename, new FileInformation(), new DokanFileInfo(0)) == 0)
            {
                return 0;
            }
            else
            {
                return -DokanNet.ERROR_FILE_NOT_FOUND;
            }
        }
 public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
 {
     IntPtr ptr;
     this.ObjectID = Interlocked.Increment(ref _objectTypeCount);
     Bid.ScopeEnter(out ptr, "<sc.SqlFileStream.ctor|API> %d# access=%d options=%d path='%ls' ", this.ObjectID, (int) access, (int) options, path);
     try
     {
         if (transactionContext == null)
         {
             throw ADP.ArgumentNull("transactionContext");
         }
         if (path == null)
         {
             throw ADP.ArgumentNull("path");
         }
         this.m_disposed = false;
         this.m_fs = null;
         this.OpenSqlFileStream(path, transactionContext, access, options, allocationSize);
         this.Name = path;
         this.TransactionContext = transactionContext;
     }
     finally
     {
         Bid.ScopeLeave(ref ptr);
     }
 }
示例#3
0
        private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _mode = mode;
            _options = options;

            if (_useAsyncIO)
                _asyncState = new AsyncState();

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, _access, options); // FileShare currently ignored

            // If the file gets created a new, we'll select the permissions for it.  Most Unix utilities by default use 666 (read and 
            // write for all), so we do the same (even though this doesn't match Windows, where by default it's possible to write out
            // a file and then execute it). No matter what we choose, it'll be subject to the umask applied by the system, such that the
            // actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions OpenPermissions =
                Interop.Sys.Permissions.S_IRUSR | Interop.Sys.Permissions.S_IWUSR |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle.
            return SafeFileHandle.Open(_path, openFlags, (int)OpenPermissions);
        }
 /// <summary>
 ///     文件分块写入流
 /// </summary>
 /// <param name="fileName">文件全名</param>
 /// <param name="fileOption">附加选项</param>
 public TmphFileBlockStream(string fileName, FileOptions fileOption = FileOptions.None)
     : base(fileName, File.Exists(fileName) ? FileMode.Open : FileMode.CreateNew, FileShare.Read, fileOption)
 {
     fileReader = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read, bufferLength,
         fileOption);
     waitHandle = wait;
 }
示例#5
0
文件: FSDrive.cs 项目: WishSummer/FS
        public DokanError CreateFile(string fileName, DokanNet.FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info)
        {
            info.DeleteOnClose = (options & FileOptions.DeleteOnClose) != 0;
            //Console.WriteLine("CreateFile: {0}, mode = {1}", fileName, mode);

            if (fileName == "\\")
            {
                return DokanError.ErrorSuccess;
            }

            Directory dir = new Directory(Util.GetPathDirectory(fileName));
            if (!dir.Exists())
            {
                return DokanError.ErrorPathNotFound;
            }

            String name = Util.GetPathFileName(fileName);

            if (name.Length == 0)
            {
                return DokanError.ErrorInvalidName;
            }
            if (name.IndexOfAny(Path.GetInvalidFileNameChars()) > -1)
            {
                return DokanError.ErrorInvalidName;
            }

            // dokan API 要求在目标文件是目录时候,设置 info.IsDirectory = true
            if (dir.Contains(name) && (dir.GetItemInfo(name).attribute & FileAttributes.Directory) != 0)
            {
                info.IsDirectory = true;
                return DokanError.ErrorSuccess;
            }

            try
            {
                File f = new File(fileName, mode);
                f.flagDeleteOnClose = info.DeleteOnClose;
                info.Context = f;
            }
            catch (FileNotFoundException)
            {
                return DokanError.ErrorFileNotFound;
            }
            catch (IOException)
            {
                return DokanError.ErrorAlreadyExists;
            }
            catch (NotImplementedException)
            {
                return DokanError.ErrorAccessDenied;
            }
            catch (Exception)
            {
                return DokanError.ErrorError;
            }

            return DokanError.ErrorSuccess;
        }
示例#6
0
        private void Init(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
        {
            if (path == null)
                throw new ArgumentNullException("path", SR.ArgumentNull_Path);
            if (path.Length == 0)
                throw new ArgumentException(SR.Argument_EmptyPath, "path");

            // don't include inheritable in our bounds check for share
            FileShare tempshare = share & ~FileShare.Inheritable;
            String badArg = null;

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
                badArg = "mode";
            else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
                badArg = "access";
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
                badArg = "share";

            if (badArg != null)
                throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);

            // NOTE: any change to FileOptions enum needs to be matched here in the error validation
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_Enum);

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum);

            // Write access validation
            if ((access & FileAccess.Write) == 0)
            {
                if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
                {
                    // No write access
                    throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access));
                }
            }

            string fullPath = PathHelpers.GetFullPathInternal(path);

            // Prevent access to your disk drives as raw block devices.
            if (fullPath.StartsWith("\\\\.\\", StringComparison.Ordinal))
                throw new ArgumentException(SR.Arg_DevicesNotSupported);

#if !PLATFORM_UNIX
            // Check for additional invalid characters.  Most invalid characters were checked above
            // in our call to Path.GetFullPath(path);
            if (HasAdditionalInvalidCharacters(fullPath))
                throw new ArgumentException(SR.Argument_InvalidPathChars);

            if (fullPath.IndexOf(':', 2) != -1)
                throw new NotSupportedException(SR.Argument_PathFormatNotSupported);
#endif

            if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
                throw new ArgumentException(SR.Argument_InvalidAppendMode);

            this._innerStream = FileSystem.Current.Open(fullPath, mode, access, share, bufferSize, options, this);
        }
 public CreateFileOperation( string path, int bufferSize, FileOptions options, FileSecurity fileSecurity )
 {
     this.path = path;
     this.bufferSize = bufferSize;
     this.options = options;
     this.fileSecurity = fileSecurity;
     tempFilePath = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() );
 }
示例#8
0
 public virtual int CreateFile(string filename, 
     FileAccess access, 
     FileShare share, 
     FileMode mode, 
     FileOptions options, 
     DokanFileInfo info)
 {
     try { return -1; }
     catch { return -1; }
 }
示例#9
0
 public Stream OpenFile(
     string path,
     FileMode fileMode,
     FileAccess fileAccess,
     FileShare fileShare,
     int bufferSize,
     FileOptions fileOptions)
 {
     return new FileStream(path, fileMode, fileAccess, fileShare, bufferSize, fileOptions);
 }
示例#10
0
 public int CreateFile(string filename, FileAccess access, FileShare share, FileMode mode, FileOptions options, DokanFileInfo info)
 {
     int result = _fileSystem.CreateFile(filename, access, share, mode, options, info);
     if (this._logging)
     {
         Console.WriteLine("CreateFile: " + filename);
         Console.WriteLine("Result: " + result);
     }
     return result;
 }
 public void DeleteOnClose_FileDeletedAfterClose(FileOptions options)
 {
     string path = GetTestFilePath();
     Assert.False(File.Exists(path));
     using (CreateFileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 0x1000, options))
     {
         Assert.True(File.Exists(path));
     }
     Assert.False(File.Exists(path));
 }
示例#12
0
        public int CreateFile(string filename, FileAccess access, FileShare share, FileMode mode, FileOptions options, DokanFileInfo info)
        {
            Console.WriteLine("Create File : " + filename);

            var response = MakeComplexRequest(Path + CREATE_FILE_REQUEST_STRING, SecurityElement.Escape(filename), (int)access, (int)share, (int)mode, (int)options, info.ProcessId);

            if (response.ContainsKey("message"))
                Console.WriteLine("Create File Message : " + response["message"]);

            return int.Parse(response["response_code"]);
        }
示例#13
0
        private AtomicFileStream(string path, string tempPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
            : base(tempPath, mode, access, share, bufferSize, options)
        {
            if (path == null)
                throw new ArgumentNullException("path");
            if (tempPath == null)
                throw new ArgumentNullException("tempPath");

            this.path = path;
            this.tempPath = tempPath;
        }
示例#14
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info,
                                  FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
                                  NtStatus result)
        {
#if TRACE
            Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0}('{1}', {2}, [{3}], [{4}], [{5}], [{6}], [{7}]) -> {8}",
                method, fileName, ToTrace(info), access, share, mode, options, attributes, result));
#endif

            return result;
        }
示例#15
0
        internal WinRTFileStream(Stream innerStream, StorageFile file, FileAccess access, FileOptions options, FileStream parent) 
            : base(parent)
        {
            Debug.Assert(innerStream != null);
            Debug.Assert(file != null);

            this._access = access;
            this._disposed = false;
            this._file = file;
            this._innerStream = innerStream;
            this._options = options;
        }
示例#16
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info,
            FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
            NtStatus result)
        {
#if TRACE
            logger.Debug(
                DokanFormat(
                    $"{method}('{fileName}', {info}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}"));
#endif

            return result;
        }
示例#17
0
        private FileStreamCompletionSource _currentOverlappedOwner; // async op currently using the preallocated overlapped

        private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
        {
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);

            int fAccess =
                ((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) |
                ((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0);

            // Our Inheritable bit was stolen from Windows, but should be set in
            // the security attributes class.  Don't leave this bit set.
            share &= ~FileShare.Inheritable;

            // Must use a valid Win32 constant here...
            if (mode == FileMode.Append)
                mode = FileMode.OpenOrCreate;

            int flagsAndAttributes = (int)options;

            // For mitigating local elevation of privilege attack through named pipes
            // make sure we always call CreateFile with SECURITY_ANONYMOUS so that the
            // named pipe server can't impersonate a high privileged client security context
            flagsAndAttributes |= (Interop.Kernel32.SecurityOptions.SECURITY_SQOS_PRESENT | Interop.Kernel32.SecurityOptions.SECURITY_ANONYMOUS);

            // Don't pop up a dialog for reading from an empty floppy drive
            uint oldMode = Interop.Kernel32.SetErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS);
            try
            {
                SafeFileHandle fileHandle = Interop.Kernel32.SafeCreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
                fileHandle.IsAsync = _useAsyncIO;

                if (fileHandle.IsInvalid)
                {
                    // Return a meaningful exception with the full path.

                    // NT5 oddity - when trying to open "C:\" as a Win32FileStream,
                    // we usually get ERROR_PATH_NOT_FOUND from the OS.  We should
                    // probably be consistent w/ every other directory.
                    int errorCode = Marshal.GetLastWin32Error();

                    if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path.Equals(Directory.InternalGetDirectoryRoot(_path)))
                        errorCode = Interop.Errors.ERROR_ACCESS_DENIED;

                    throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path);
                }

                return fileHandle;
            }
            finally
            {
                Interop.Kernel32.SetErrorMode(oldMode);
            }
        }
示例#18
0
 public NtStatus CreateFile(
     string filename,
     FileAccess access,
     FileShare share,
     FileMode mode,
     FileOptions options,
     FileAttributes attributes,
     DokanFileInfo info)
 {
     if (info.IsDirectory && mode == FileMode.CreateNew)
         return DokanResult.AccessDenied;
     return DokanResult.Success;
 }
示例#19
0
        public static AtomicFileStream Open(string path, string tempPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
        {
            if (access == FileAccess.Read)
                throw new ArgumentException("If you're just opening the file for reading, AtomicFileStream won't help you at all");

            if (File.Exists(tempPath))
                File.Delete(tempPath);

            if (File.Exists(path) && (mode == FileMode.Append || mode == FileMode.Open || mode == FileMode.OpenOrCreate))
                File.Copy(path, tempPath);

            return new AtomicFileStream(path, tempPath, mode, access, share, bufferSize, options);
        }
示例#20
0
 public static FileMap FromFile(string path, FileMapProtect prot, int offset, int length, FileOptions options)
 {
     FileStream stream;
     FileMap map;
     try { stream = new FileStream(path, FileMode.Open, (prot == FileMapProtect.ReadWrite) ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read, 8, options); }
     catch //File is currently in use, but we can copy it to a temp location and read that
     {
         string tempPath = Path.GetTempFileName();
         File.Copy(path, tempPath, true);
         stream = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 8, options | FileOptions.DeleteOnClose);
     }
     try { map = FromStreamInternal(stream, prot, offset, length); }
     catch (Exception x) { stream.Dispose(); throw x; }
     map._path = path; //In case we're using a temp file
     return map;
 }
示例#21
0
        private void Init(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
        {
            if (path == null)
                throw new ArgumentNullException("path", SR.ArgumentNull_Path);
            if (path.Length == 0)
                throw new ArgumentException(SR.Argument_EmptyPath, "path");

            // don't include inheritable in our bounds check for share
            FileShare tempshare = share & ~FileShare.Inheritable;
            String badArg = null;

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
                badArg = "mode";
            else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
                badArg = "access";
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
                badArg = "share";

            if (badArg != null)
                throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);

            // NOTE: any change to FileOptions enum needs to be matched here in the error validation
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_Enum);

            if (bufferSize <= 0)
                throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum);

            // Write access validation
            if ((access & FileAccess.Write) == 0)
            {
                if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
                {
                    // No write access, mode and access disagree but flag access since mode comes first
                    throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), "access");
                }
            }

            string fullPath = PathHelpers.GetFullPathInternal(path);

            ValidatePath(fullPath, "path");

            if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
                throw new ArgumentException(SR.Argument_InvalidAppendMode, "access");

            this._innerStream = FileSystem.Current.Open(fullPath, mode, access, share, bufferSize, options, this);
        }
示例#22
0
        // file apis
        public int CreateFile(string filename, FileAccess access, FileShare share, FileMode mode, FileOptions options, DokanFileInfo info)
        {
            info.IsDirectory = flacFs_.IsDirectory(filename);
            if (info.IsDirectory)
            {
                return 0;
            }

            long handle = flacFs_.OpenFile(filename);
            if (handle != FlacFs.INVALID_HANDLE)
            {
                info.Context = handle;
                return 0;
            }

            return -DokanNet.ERROR_FILE_NOT_FOUND;
        }
示例#23
0
文件: Program.cs 项目: stux2000/dokan
 public int CreateFile(String filename, FileAccess access, FileShare share,
     FileMode mode, FileOptions options, DokanFileInfo info)
 {
     string path = GetPath(filename);
     info.Context = count_++;
     if (File.Exists(path))
     {
         return 0;
     }
     else if(Directory.Exists(path))
     {
         info.IsDirectory = true;
         return 0;
     }
     else
     {
         return -DokanNet.ERROR_FILE_NOT_FOUND;
     }
 }
 public FileStream(string file, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
 {
     try
     {
         this.fileOptions = options;
         this.name = file;
         this.CheckAccess(mode, access);
         StorageFile storageFile;
         switch (mode)
         {
             case FileMode.CreateNew:
             case FileMode.Create:
             case FileMode.OpenOrCreate:
             case FileMode.Append:
                 storageFile = FileStream.CreateFile(file, mode, access);
                 break;
             case FileMode.Open:
             case FileMode.Truncate:
                 storageFile = FileStream.OpenFile(file, mode, access);
                 break;
             default:
                 throw new ArgumentException("Unknown file mode");
         }
         IAsyncOperation<IRandomAccessStream> source = storageFile.OpenAsync(FileStream.GetAccessMode(access));
         WindowsRuntimeSystemExtensions.AsTask<IRandomAccessStream>(source).Wait();
         this.backend = (FileRandomAccessStream)source.GetResults();
         if (mode == FileMode.Truncate)
         {
             this.backend.Size = 0UL;
         }
         else
         {
             if (mode != FileMode.Append)
                 return;
             this.backend.Seek(this.backend.Size);
         }
     }
     catch (Exception ex)
     {
         throw FileStream.RethrowException(ex);
     }
 }
 public IFile CreateFile(string file, FileMode fileMode, FileAccess fileAccess, FileShare fileShare,
     FileSystemRights fileSystemRights, FileOptions fileOptions, FileSecurity fileSecurity)
 {
     using (var tranHandle = GetKtmTransactionHandle())
     {
         int dwFlagsAndAttributes = (int) fileOptions;
         dwFlagsAndAttributes |= 0x100000;
         NativeMethods.FileAccess faccess = NativeFileEnums.TranslateFileAccess(fileAccess);
         NativeMethods.FileShare fshare = NativeFileEnums.TranslateFileShare(fileShare);
         NativeMethods.FileMode fmode = NativeFileEnums.TranslateFileMode(fileMode);
         using (SafeFileHandle fileHandle = NativeMethods.CreateFileTransacted(file, faccess, fshare, IntPtr.Zero, fmode,
                                                                               dwFlagsAndAttributes, IntPtr.Zero, tranHandle,
                                                                               IntPtr.Zero, IntPtr.Zero))
         {
             if (fileHandle.IsInvalid)
                 throw new InvalidOperationException();
         }
         return GetFile(file);
     }
 }
        public void ValidFileOptions(FileOptions option)
        {
            byte[] data = new byte[c_DefaultBufferSize];
            new Random(1).NextBytes(data);

            using (FileStream fs = CreateFileStream(GetTestFilePath(), FileMode.Create, FileAccess.ReadWrite, FileShare.Read, c_DefaultBufferSize, option))
            {
                // make sure we can write, seek, and read data with this option set
                fs.Write(data, 0, data.Length);
                fs.Position = 0;

                byte[] tmp = new byte[data.Length];
                int totalRead = 0;
                while (true)
                {
                    int numRead = fs.Read(tmp, totalRead, tmp.Length - totalRead);
                    Assert.InRange(numRead, 0, tmp.Length);
                    if (numRead == 0)
                        break;
                    totalRead += numRead;
                }
            }
        }
        public UnbufferedFileStream(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, BufferManager bufferManager)
        {
            _path = path;
            _bufferManager = bufferManager;

            {
                const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;

                _stream = new FileStream(path, mode, access, share, 8, options | FileFlagNoBuffering);
            }

            _blockInfo = new BlockInfo();
            {
                _blockInfo.IsUpdated = false;
                _blockInfo.Position = -1;
                _blockInfo.Offset = 0;
                _blockInfo.Count = 0;
                _blockInfo.Value = _bufferManager.TakeBuffer(SectorSize);
            }

            _position = _stream.Position;
            _length = _stream.Length;
        }
示例#28
0
        internal OSFileStreamStrategy(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize)
        {
            string fullPath = Path.GetFullPath(path);

            _access = access;

            _fileHandle = SafeFileHandle.Open(fullPath, mode, access, share, options, preallocationSize);

            try
            {
                if (mode == FileMode.Append && CanSeek)
                {
                    _appendStart = _filePosition = Length;
                }
                else
                {
                    _appendStart = -1;
                }
            }
            catch
            {
                // If anything goes wrong while setting up the stream, make sure we deterministically dispose
                // of the opened handle.
                _fileHandle.Dispose();
                _fileHandle = null !;
                throw;
            }
        }
示例#29
0
 public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
 {
     EnsureBackgroundThread();
     return(SynchronousResultOf(OpenAsync(fullPath, mode, access, share, bufferSize, options, parent)));
 }
示例#30
0
 /// <summary>
 /// Create new file stream for <paramref name="targetFileInfo"/>.
 /// </summary>
 /// <param name="targetFileInfo">Target file info</param>
 /// <param name="mode">mode of the stream</param>
 /// <param name="access">Access permission</param>
 /// <param name="share">File share type</param>
 /// <param name="bufferSize">Buffer size</param>
 /// <param name="options">File options</param>
 public static FileStream CreateStream(this FileInfo targetFileInfo, FileMode mode,
                                       FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read,
                                       int bufferSize    = StdLookUps.DefaultFileBufferSize, FileOptions options = FileOptions.Asynchronous)
 {
     return(new FileStream(targetFileInfo.FullName, mode, access, share, bufferSize, options));
 }
示例#31
0
        public static FileMap FromFile(string path, FileMapProtect prot, uint offset, int length, FileOptions options)
        {
            FileStream stream;
            FileMap    map;

            try { stream = new FileStream(path, FileMode.Open, (prot == FileMapProtect.ReadWrite) ? FileAccess.ReadWrite : FileAccess.Read, FileShare.Read, 8, options); }
            catch //File is currently in use, but we can copy it to a temp location and read that
            {
                string tempPath = Path.GetTempFileName();
                File.Copy(path, tempPath, true);
                stream = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, 8, options | FileOptions.DeleteOnClose);
            }
            try { map = FromStreamInternal(stream, prot, offset, length); }
            catch (Exception) { stream.Dispose(); throw; }
            map._path = path; //In case we're using a temp file
            stream.Dispose();
            return(map);
        }
 public Task <Stream> OpenAsync(AbsolutePath path, FileAccess fileAccess, FileMode fileMode, FileShare share, FileOptions options, int bufferSize)
 {
     throw new NotImplementedException();
 }
 protected virtual FileStream CreateFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
 {
     return(new FileStream(path, mode, access, share, bufferSize, options));
 }
        => share & ~FileShare.Inheritable;     // FileShare.Inheritable is handled in GetObjectAttributes

        private static FileAttributes GetFileAttributes(FileOptions options)
        => (options & FileOptions.Encrypted) != 0 ? FileAttributes.Encrypted : 0;
示例#35
0
#pragma warning restore IDE0060

        private static FileStreamStrategy ChooseStrategyCore(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize, UnixFileMode?unixCreateMode) =>
        new UnixFileStreamStrategy(path, mode, access, share, options, preallocationSize, unixCreateMode);
示例#36
0
 public override NtStatus Open(string fileName, FileAccess access, FileShare share, bool create, bool append,
                               FileOptions options,
                               FileAttributes attributes, DokanFileInfo fileInfo)
 {
     return(DokanResult.Success);
 }
示例#37
0
 public static FileStream Create(string path, int bufferSize, FileOptions options)
 => new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize, options);
示例#38
0
 public Stream OpenFile(string path, FileMode fileMode, FileAccess fileAccess, FileShare fileShare,
                        int bufferSize,
                        FileOptions fileOptions)
 {
     throw new NotImplementedException();
 }
示例#39
0
        public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes,
            DokanFileInfo info)
        {
            var path = GetPath(fileName);

            bool pathExists = true;
            bool pathIsDirectory = false;

            bool readWriteAttributes = (access & DataAccess) == 0;

            bool readAccess = (access & DataWriteAccess) == 0;

            try
            {
                pathIsDirectory = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
            }
            catch (IOException)
            {
                pathExists = false;
            }

            switch (mode)
            {
                case FileMode.Open:

                    if (pathExists)
                    {
                        if (readWriteAttributes || pathIsDirectory)
                        // check if driver only wants to read attributes, security info, or open directory
                        {
                            info.IsDirectory = pathIsDirectory;
                            info.Context = new object();
                            // must set it to someting if you return DokanError.Success

                            return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.Success);
                        }
                    }
                    else
                    {
                        return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound);
                    }
                    break;

                case FileMode.CreateNew:
                    if (pathExists)
                        return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.FileExists);
                    break;

                case FileMode.Truncate:
                    if (!pathExists)
                        return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound);
                    break;

                default:
                    break;
            }

            try
            {
                info.Context = new FileStream(path, mode, readAccess ? System.IO.FileAccess.Read : System.IO.FileAccess.ReadWrite, share, 4096, options);
            }
            catch (UnauthorizedAccessException) // don't have access rights
            {
                return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.AccessDenied);
            }

            return Trace("CreateFile", fileName, info, access, share, mode, options, attributes, DokanResult.Success);
        }
示例#40
0
        /// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlTypes/SqlFileStream.xml' path='docs/members[@name="SqlFileStream"]/ctor2/*' />
        public SqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
        {
            using (TryEventScope.Create(SqlClientEventSource.Log.TryScopeEnterEvent("SqlFileStream.ctor | API | Object Id {0} | Access {1} | Options {2} | Path '{3}'", ObjectID, (int)access, (int)options, path)))
            {
                //-----------------------------------------------------------------
                // precondition validation

                if (transactionContext == null)
                {
                    throw ADP.ArgumentNull("transactionContext");
                }

                if (path == null)
                {
                    throw ADP.ArgumentNull("path");
                }

                //-----------------------------------------------------------------

                _m_disposed = false;
                _m_fs       = null;

                OpenSqlFileStream(path, transactionContext, access, options, allocationSize);

                // only set internal state once the file has actually been successfully opened
                Name = path;
                TransactionContext = transactionContext;
            }
        }
示例#41
0
 public FileStream Create(string path, int bufferSize, FileOptions options)
 {
     return(File.Create(path, bufferSize, options));
 }
示例#42
0
 /// <summary>
 /// Create new stream writer for <paramref name="targetFileInfo"/>.
 /// </summary>
 /// <param name="targetFileInfo">Target file info</param>
 /// <param name="enc">Text encoding to use. If null, then <seealso cref="Encoding.UTF8"/> is used.</param>
 /// <param name="appendToFile">If true, existing file is appended or new file is created. If false, existing file is
 /// truncated or new file is created.</param>
 /// <param name="share">File share type</param>
 /// <param name="bufferSize">Buffer size</param>
 /// <param name="options">File options</param>
 /// <param name="autoFlush">True to enable auto-flushing else false</param>
 public static StreamWriter CreateStreamWriter(this FileInfo targetFileInfo, Encoding enc = null,
                                               bool appendToFile = false, FileShare share = FileShare.Read,
                                               int bufferSize    = StdLookUps.DefaultFileBufferSize, FileOptions options = FileOptions.Asynchronous,
                                               bool autoFlush    = false)
 {
     return(targetFileInfo.CreateStream(appendToFile ? FileMode.Append : FileMode.Create,
                                        FileAccess.ReadWrite, share, bufferSize, options).CreateWriter(enc, bufferSize, true, autoFlush));
 }
示例#43
0
 public override NtStatus Create(string fileName, FileAccess access, FileShare share, bool overwrite,
                                 FileOptions options,
                                 FileAttributes attributes, DokanFileInfo info)
 {
     return(DokanResult.Success);
 }
        private static DesiredAccess GetDesiredAccess(FileAccess access, FileMode fileMode, FileOptions options)
        {
            DesiredAccess result = DesiredAccess.FILE_READ_ATTRIBUTES | DesiredAccess.SYNCHRONIZE; // default values used by CreateFileW

            if ((access & FileAccess.Read) != 0)
            {
                result |= DesiredAccess.FILE_GENERIC_READ;
            }
            if ((access & FileAccess.Write) != 0)
            {
                result |= DesiredAccess.FILE_GENERIC_WRITE;
            }
            if (fileMode == FileMode.Append)
            {
                result |= DesiredAccess.FILE_APPEND_DATA;
            }
            if ((options & FileOptions.DeleteOnClose) != 0)
            {
                result |= DesiredAccess.DELETE; // required by FILE_DELETE_ON_CLOSE
            }

            return(result);
        }
示例#45
0
        /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary>
        /// <param name="mode">The FileMode provided to the stream's constructor.</param>
        /// <param name="access">The FileAccess provided to the stream's constructor</param>
        /// <param name="options">The FileOptions provided to the stream's constructor</param>
        /// <returns>The flags value to be passed to the open system call.</returns>
        private static Interop.Sys.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options)
        {
            // Translate FileMode.  Most of the values map cleanly to one or more options for open.
            Interop.Sys.OpenFlags flags = default(Interop.Sys.OpenFlags);
            switch (mode)
            {
            default:
            case FileMode.Open:     // Open maps to the default behavior for open(...).  No flags needed.
                break;

            case FileMode.Append:     // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later
            case FileMode.OpenOrCreate:
                flags |= Interop.Sys.OpenFlags.O_CREAT;
                break;

            case FileMode.Create:
                flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_TRUNC);
                break;

            case FileMode.CreateNew:
                flags |= (Interop.Sys.OpenFlags.O_CREAT | Interop.Sys.OpenFlags.O_EXCL);
                break;

            case FileMode.Truncate:
                flags |= Interop.Sys.OpenFlags.O_TRUNC;
                break;
            }

            // Translate FileAccess.  All possible values map cleanly to corresponding values for open.
            switch (access)
            {
            case FileAccess.Read:
                flags |= Interop.Sys.OpenFlags.O_RDONLY;
                break;

            case FileAccess.ReadWrite:
                flags |= Interop.Sys.OpenFlags.O_RDWR;
                break;

            case FileAccess.Write:
                flags |= Interop.Sys.OpenFlags.O_WRONLY;
                break;
            }

            // Translate some FileOptions; some just aren't supported, and others will be handled after calling open.
            switch (options)
            {
            case FileOptions.Asynchronous:        // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true
            case FileOptions.DeleteOnClose:       // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose
            case FileOptions.Encrypted:           // Encrypted does not have an equivalent on Unix and is ignored.
            case FileOptions.RandomAccess:        // Implemented after open if posix_fadvise is available
            case FileOptions.SequentialScan:      // Implemented after open if posix_fadvise is available
                break;

            case FileOptions.WriteThrough:
                flags |= Interop.Sys.OpenFlags.O_SYNC;
                break;
            }

            return(flags);
        }
示例#46
0
        /// <summary>Initializes a stream for reading or writing a Unix file.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="mode">How the file should be opened.</param>
        /// <param name="access">Whether the file will be read, written, or both.</param>
        /// <param name="share">What other access to the file should be allowed.  This is currently ignored.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="options">Additional options for working with the file.</param>
        internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
            : base(parent)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _path         = path;
            _access       = access;
            _mode         = mode;
            _options      = options;
            _bufferLength = bufferSize;
            _useAsyncIO   = (options & FileOptions.Asynchronous) != 0;

            // Translate the arguments into arguments for an open call
            Interop.Sys.OpenFlags    openFlags       = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored
            Interop.libc.Permissions openPermissions = Interop.libc.Permissions.S_IRWXU;                       // creator has read/write/execute permissions; no permissions for anyone else

            // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized.
            _fileHandle         = SafeFileHandle.Open(path, openFlags, (int)openPermissions);
            _fileHandle.IsAsync = _useAsyncIO;

            // Lock the file if requested via FileShare.  This is only advisory locking. FileShare.None implies an exclusive
            // lock on the file and all other modes use a shared lock.  While this is not as granular as Windows, not mandatory,
            // and not atomic with file opening, it's better than nothing.
            try
            {
                Interop.libc.LockOperations lockOperation = (share == FileShare.None) ? Interop.libc.LockOperations.LOCK_EX : Interop.libc.LockOperations.LOCK_SH;
                SysCall <Interop.libc.LockOperations, int>((fd, op, _) => Interop.libc.flock(fd, op), lockOperation | Interop.libc.LockOperations.LOCK_NB);
            }
            catch
            {
                _fileHandle.Dispose();
                throw;
            }

            // Perform additional configurations on the stream based on the provided FileOptions
            PostOpenConfigureStreamFromOptions();

            // Jump to the end of the file if opened as Append.
            if (_mode == FileMode.Append)
            {
                _appendStart = SeekCore(0, SeekOrigin.End);
            }
        }
示例#47
0
        DokanError IDokanOperations.CreateFile(string fileName, FileAccess access, FileShare share,
                                               FileMode mode, FileOptions options,
                                               FileAttributes attributes, DokanFileInfo info)
        {
            if (fileName.EndsWith("desktop.ini", StringComparison.OrdinalIgnoreCase) ||
                fileName.EndsWith("autorun.inf", StringComparison.OrdinalIgnoreCase)) //....
            {
                return(DokanError.ErrorFileNotFound);
            }

            string path = GetUnixPath(fileName);
            //  var  sftpFileAttributes = GetAttributes(path);
            var sftpFileAttributes = _cache.Get(path) as SftpFileAttributes;

            if (sftpFileAttributes == null)
            {
                Log("cache miss");

                sftpFileAttributes = GetAttributes(path);
                if (sftpFileAttributes != null)
                {
                    _cache.Add(path, sftpFileAttributes, DateTimeOffset.UtcNow.AddSeconds(_attributeCacheTimeout));
                }
            }

            Log("Open| Name:{0},\n Mode:{1},\n Share{2},\n Disp:{3},\n Flags{4},\n Attr:{5}\n", fileName, access,
                share, mode, options, attributes);

            // Check if FILE_FLAG_DELETE_ON_CLOSE is set
            if ((options &= FileOptions.DeleteOnClose) != 0)
            {
                _deleteOnCloseFiles.Add(fileName);
            }

            switch (mode)
            {
            case FileMode.Open:
                if (sftpFileAttributes != null)
                {
                    if (((uint)access & 0xe0000027) == 0 || sftpFileAttributes.IsDirectory)
                    //check if only wants to read attributes,security info or open directory
                    {
                        Log("JustInfo:{0},{1}", fileName, sftpFileAttributes.IsDirectory);
                        info.IsDirectory = sftpFileAttributes.IsDirectory;
                        info.Context     = new SftpContext(sftpFileAttributes);
                        return(DokanError.ErrorSuccess);
                    }
                }
                else
                {
                    return(DokanError.ErrorFileNotFound);
                }
                break;

            case FileMode.CreateNew:
                if (sftpFileAttributes != null)
                {
                    return(DokanError.ErrorAlreadyExists);
                }

                InvalidateParentCache(fileName);     // cache invalidate
                break;

            case FileMode.Truncate:
                if (sftpFileAttributes == null)
                {
                    return(DokanError.ErrorFileNotFound);
                }
                InvalidateParentCache(fileName);
                _cache.Remove(path);
                break;

            default:

                InvalidateParentCache(fileName);
                break;
            }
            Log("NotJustInfo:{0}-{1}", info.Context, mode);
            try
            {
                info.Context = new SftpContext(_sftpSession, path, mode,
                                               ((ulong)access & 0x40010006) == 0
                                                   ? System.IO.FileAccess.Read
                                                   : System.IO.FileAccess.ReadWrite, sftpFileAttributes);
            }
            catch (SshException) // Don't have access rights or try to read broken symlink
            {
                return(DokanError.ErrorAccessDenied);
            }


            return(DokanError.ErrorSuccess);
        }
示例#48
0
 /// <summary>
 /// Create new JSON writer for <paramref name="targetFileInfo"/> with custom properties.
 /// </summary>
 /// <param name="targetFileInfo">Target file info</param>
 /// <param name="enc">Text encoding to use. If null, then <seealso cref="Encoding.UTF8"/> is used.</param>
 /// <param name="appendToFile">If true, existing file is appended or new file is created. If false, existing file is
 /// truncated or new file is created.</param>
 /// <param name="share">File share type</param>
 /// <param name="bufferSize">Buffer size</param>
 /// <param name="options">File options</param>
 /// <param name="autoFlush">True to enable auto-flushing else false</param>
 public static JsonTextWriter CreateJsonWriter(this FileInfo targetFileInfo, Encoding enc = null,
                                               bool appendToFile = false, FileShare share = FileShare.Read,
                                               int bufferSize    = StdLookUps.DefaultFileBufferSize, FileOptions options = FileOptions.Asynchronous,
                                               bool autoFlush    = false)
 {
     return(targetFileInfo.CreateStreamWriter(enc, appendToFile, share, bufferSize, options, autoFlush)
            .CreateJsonWriter());
 }
示例#49
0
        public override NtStatus CreateFile(string fileName, DokanNet.FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, IDokanFileInfo info)
        {
            if (IsBadName(fileName))
            {
                return(NtStatus.ObjectNameInvalid);
            }
            if ((access & ModificationAttributes) != 0)
            {
                return(NtStatus.DiskFull);
            }

            var item = GetFile(fileName);

            if (item == null)
            {
                return(DokanResult.FileNotFound);
            }
            if (item.Info.Key != null && !item.Info.IsDirectory)
            {
                if ((access & (DokanNet.FileAccess.ReadData | DokanNet.FileAccess.GenericRead)) != 0)
                {
                    LastAccessed = DateTime.Now;
                    Console.WriteLine("SharpCompressFs ReadData: " + fileName);

                    lock (this)
                    {
                        var entry = extractor.Entries.First(a => a.Key.EndsWith(fileName));

                        if (((SharpCompress.Common.Rar.Headers.FileHeader)entry.RarParts.First().FileHeader).IsStored)
                        {
                            // stored
                            info.Context = new RarStoreStream(entry);
                        }
                        else
                        {
                            // 5mb
                            if (entry.CompressedSize <= 1024 * 1024 * 5)
                            {
                                info.Context = new MemoryStream();
                                entry.OpenEntryStream().CopyTo((MemoryStream)info.Context);
                                return(NtStatus.Success);
                            }
                            //info.Context = new MemoryStream(entry.OpenEntryStream());
                            return(NtStatus.AccessDenied);
                        }
                    }
                }
                return(NtStatus.Success);
            }
            else
            {
                info.IsDirectory = true;
                return(NtStatus.Success);
            }
        }
示例#50
0
 private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
 {
     throw new NotImplementedException();
 }
示例#51
0
        internal static void ValidateArguments(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, long preallocationSize)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
            }
            else if (path.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
            }

            // don't include inheritable in our bounds check for share
            FileShare tempshare = share & ~FileShare.Inheritable;
            string?   badArg    = null;

            if (mode < FileMode.CreateNew || mode > FileMode.Append)
            {
                badArg = nameof(mode);
            }
            else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
            {
                badArg = nameof(access);
            }
            else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
            {
                badArg = nameof(share);
            }

            if (badArg != null)
            {
                throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);
            }

            // NOTE: any change to FileOptions enum needs to be matched here in the error validation
            if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum);
            }
            else if (bufferSize < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_NeedNonNegNum(nameof(bufferSize));
            }
            else if (preallocationSize < 0)
            {
                ThrowHelper.ThrowArgumentOutOfRangeException_NeedNonNegNum(nameof(preallocationSize));
            }

            // Write access validation
            if ((access & FileAccess.Write) == 0)
            {
                if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
                {
                    // No write access, mode and access disagree but flag access since mode comes first
                    throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access));
                }
            }

            if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
            {
                throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access));
            }

            if (preallocationSize > 0)
            {
                ValidateArgumentsForPreallocation(mode, access);
            }

            SerializationGuard(access);
        }
示例#52
0
        private async Task <FileStreamBase> OpenAsync(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
        {
            // When trying to open the root directory, we need to throw an Access Denied
            if (PathInternal.GetRootLength(fullPath) == fullPath.Length)
            {
                throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_ACCESS_DENIED, fullPath);
            }

            // Win32 CreateFile returns ERROR_PATH_NOT_FOUND when given a path that ends with '\'
            if (PathHelpers.EndsInDirectorySeparator(fullPath))
            {
                throw Win32Marshal.GetExceptionForWin32Error(Interop.mincore.Errors.ERROR_PATH_NOT_FOUND, fullPath);
            }

            StorageFile file = null;

            // FileMode
            if (mode == FileMode.Open || mode == FileMode.Truncate)
            {
                file = await StorageFile.GetFileFromPathAsync(fullPath).TranslateWinRTTask(fullPath);
            }
            else
            {
                CreationCollisionOption collisionOptions;

                switch (mode)
                {
                case FileMode.Create:
                    collisionOptions = CreationCollisionOption.ReplaceExisting;
                    break;

                case FileMode.CreateNew:
                    collisionOptions = CreationCollisionOption.FailIfExists;
                    break;

                case FileMode.Append:
                case FileMode.OpenOrCreate:
                default:
                    collisionOptions = CreationCollisionOption.OpenIfExists;
                    break;
                }

                string directoryPath, fileName;
                PathHelpers.SplitDirectoryFile(fullPath, out directoryPath, out fileName);

                StorageFolder directory = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);

                file = await directory.CreateFileAsync(fileName, collisionOptions).TranslateWinRTTask(fullPath);
            }

            // FileAccess: WinRT doesn't support FileAccessMode.Write so we upgrade to ReadWrite
            FileAccessMode accessMode = ((access & FileAccess.Write) != 0) ? FileAccessMode.ReadWrite : FileAccessMode.Read;

            // FileShare: cannot translate StorageFile uses a different sharing model (oplocks) that is controlled via FileAccessMode

            // FileOptions: ignore most values of FileOptions as they are hints and are not supported by WinRT.
            // FileOptions.Encrypted is not a hint, and not supported by WinRT, but there is precedent for ignoring this (FAT).
            // FileOptions.DeleteOnClose should result in an UnauthorizedAccessException when
            //   opening a file that can only be read, but we cannot safely reproduce that behavior
            //   in WinRT without actually deleting the file.
            //   Instead the failure will occur in the finalizer for WinRTFileStream and be ignored.

            // open our stream
            Stream stream = (await file.OpenAsync(accessMode).TranslateWinRTTask(fullPath)).AsStream(bufferSize);

            if (mode == FileMode.Append)
            {
                // seek to end.
                stream.Seek(0, SeekOrigin.End);
            }
            else if (mode == FileMode.Truncate)
            {
                // truncate stream to 0
                stream.SetLength(0);
            }

            return(new WinRTFileStream(stream, file, access, options, parent));
        }
示例#53
0
        public NtStatus CreateFile(string fileName, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, DokanFileInfo info)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            // HACK: Fix for Bug in Dokany related to a missing trailing slash for directory names
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = @"\";
            }
            // HACK: Fix for Bug in Dokany related to a call to CreateFile with a fileName of '\*'
            else if (fileName == @"\*" && access == FileAccess.ReadAttributes)
            {
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success));
            }

            if (fileName == @"\")
            {
                info.IsDirectory = true;
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success));
            }

            fileName = fileName.TrimEnd(Path.DirectorySeparatorChar);

            var parent = GetItem(Path.GetDirectoryName(fileName)) as CloudDirectoryNode;

            if (parent == null)
            {
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.PathNotFound));
            }

            var itemName = Path.GetFileName(fileName);
            var item     = parent.GetChildItemByName(drive, itemName);
            var fileItem = default(CloudFileNode);

            switch (mode)
            {
            case FileMode.Create:
                fileItem = item as CloudFileNode;
                if (fileItem != null)
                {
                    fileItem.Truncate(drive);
                }
                else
                {
                    fileItem = parent.NewFileItem(drive, itemName);
                }

                info.Context = new StreamContext(fileItem, FileAccess.WriteData);

                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success));

            case FileMode.Open:
                fileItem = item as CloudFileNode;
                if (fileItem != null)
                {
                    if (access.HasFlag(FileAccess.ReadData))
                    {
                        info.Context = new StreamContext(fileItem, FileAccess.ReadData);
                    }
                    else if (access.HasFlag(FileAccess.WriteData))
                    {
                        info.Context = new StreamContext(fileItem, FileAccess.WriteData);
                    }
                    else if (access.HasFlag(FileAccess.Delete))
                    {
                        info.Context = new StreamContext(fileItem, FileAccess.Delete);
                    }
                    else if (!access.HasFlag(FileAccess.ReadAttributes))
                    {
                        return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.NotImplemented));
                    }
                }
                else
                {
                    info.IsDirectory = item != null;
                }

                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, item != null ? DokanResult.Success : DokanResult.FileNotFound));

            case FileMode.OpenOrCreate:
                fileItem = item as CloudFileNode ?? parent.NewFileItem(drive, itemName);

                if (access.HasFlag(FileAccess.ReadData) && !access.HasFlag(FileAccess.WriteData))
                {
                    info.Context = new StreamContext(fileItem, FileAccess.ReadData);
                }
                else
                {
                    info.Context = new StreamContext(fileItem, FileAccess.WriteData);
                }

                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success));

            case FileMode.CreateNew:
                if (item != null)
                {
                    return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, info.IsDirectory ? DokanResult.AlreadyExists : DokanResult.FileExists));
                }

                if (info.IsDirectory)
                {
                    parent.NewDirectoryItem(drive, itemName);
                }
                else
                {
                    fileItem = parent.NewFileItem(drive, itemName);

                    info.Context = new StreamContext(fileItem, FileAccess.WriteData);
                }
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success));

            case FileMode.Append:
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.NotImplemented));

            case FileMode.Truncate:
                //fileItem = item as CloudFileNode;
                //if (fileItem == null)
                //    return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.FileNotFound);

                //fileItem.Truncate(drive);

                //info.Context = new StreamContext(fileItem, FileAccess.WriteData);

                //return Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.Success);
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.NotImplemented));

            default:
                return(Trace(nameof(CreateFile), fileName, info, access, share, mode, options, attributes, DokanResult.NotImplemented));
            }
        }
 public static void SetFileOptions(FileOptions options)
 {
     fileOptions = options;
 }
        internal static unsafe (uint status, IntPtr handle) NtCreateFile(ReadOnlySpan <char> path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize)
        {
            // For mitigating local elevation of privilege attack through named pipes
            // make sure we always call NtCreateFile with SECURITY_ANONYMOUS so that the
            // named pipe server can't impersonate a high privileged client security context
            SECURITY_QUALITY_OF_SERVICE securityQualityOfService = new SECURITY_QUALITY_OF_SERVICE(
                ImpersonationLevel.Anonymous, // SECURITY_ANONYMOUS
                ContextTrackingMode.Static,
                effectiveOnly: false);

            return(CreateFile(
                       path: path,
                       rootDirectory: IntPtr.Zero,
                       createDisposition: GetCreateDisposition(mode),
                       desiredAccess: GetDesiredAccess(access, mode, options),
                       shareAccess: GetShareAccess(share),
                       fileAttributes: GetFileAttributes(options),
                       createOptions: GetCreateOptions(options),
                       objectAttributes: GetObjectAttributes(share),
                       preallocationSize: &preallocationSize,
                       securityQualityOfService: &securityQualityOfService));
        }
示例#56
0
        internal static FileStreamStrategy ChooseStrategy(FileStream fileStream, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, long preallocationSize)
        {
            FileStreamStrategy strategy =
                EnableBufferingIfNeeded(ChooseStrategyCore(path, mode, access, share, options, preallocationSize), bufferSize);

            return(WrapIfDerivedType(fileStream, strategy));
        }
示例#57
0
        /// <summary>Initializes a stream for reading or writing a Unix file.</summary>
        /// <param name="path">The path to the file.</param>
        /// <param name="mode">How the file should be opened.</param>
        /// <param name="access">Whether the file will be read, written, or both.</param>
        /// <param name="share">What other access to the file should be allowed.  This is currently ignored.</param>
        /// <param name="bufferSize">The size of the buffer to use when buffering.</param>
        /// <param name="options">Additional options for working with the file.</param>
        internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
            : base(parent)
        {
            // FileStream performs most of the general argument validation.  We can assume here that the arguments
            // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.)
            // Store the arguments
            _path = path;
            _access = access;
            _mode = mode;
            _options = options;
            _bufferLength = bufferSize;
            if ((options & FileOptions.Asynchronous) != 0)
            {
                _useAsyncIO = true;
                _asyncState = new AsyncState();
            }

            // Translate the arguments into arguments for an open call.
            Interop.Sys.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored

            // If the file gets created a new, we'll select the permissions for it.  Most utilities by default use 666 (read and 
            // write for all). However, on Windows it's possible to write out a file and then execute it.  To maintain that similarity, 
            // we use 766, so that in addition the user has execute privileges. No matter what we choose, it'll be subject to the umask 
            // applied by the system, such that the actual permissions will typically be less than what we select here.
            const Interop.Sys.Permissions openPermissions =
                Interop.Sys.Permissions.S_IRWXU |
                Interop.Sys.Permissions.S_IRGRP | Interop.Sys.Permissions.S_IWGRP |
                Interop.Sys.Permissions.S_IROTH | Interop.Sys.Permissions.S_IWOTH;

            // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized.
            _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions);
            try
            {
                _fileHandle.IsAsync = _useAsyncIO;

                // Lock the file if requested via FileShare.  This is only advisory locking. FileShare.None implies an exclusive 
                // lock on the file and all other modes use a shared lock.  While this is not as granular as Windows, not mandatory, 
                // and not atomic with file opening, it's better than nothing.  Some kinds of files, e.g. FIFOs, don't support
                // locking on some platforms, e.g. OSX, and so if flock returns ENOTSUP, we similarly treat it as a hint and ignore it,
                // as we don't want to entirely prevent usage of a particular file simply because locking isn't supported.
                Interop.Sys.LockOperations lockOperation = (share == FileShare.None) ? Interop.Sys.LockOperations.LOCK_EX : Interop.Sys.LockOperations.LOCK_SH;
                CheckFileCall(Interop.Sys.FLock(_fileHandle, lockOperation | Interop.Sys.LockOperations.LOCK_NB), ignoreNotSupported: true);

                // These provide hints around how the file will be accessed.  Specifying both RandomAccess
                // and Sequential together doesn't make sense as they are two competing options on the same spectrum,
                // so if both are specified, we prefer RandomAccess (behavior on Windows is unspecified if both are provided).
                Interop.Sys.FileAdvice fadv =
                    (_options & FileOptions.RandomAccess) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_RANDOM :
                    (_options & FileOptions.SequentialScan) != 0 ? Interop.Sys.FileAdvice.POSIX_FADV_SEQUENTIAL :
                    0;
                if (fadv != 0)
                {
                    CheckFileCall(Interop.Sys.PosixFAdvise(_fileHandle, 0, 0, fadv), 
                        ignoreNotSupported: true); // just a hint.
                }

                // Jump to the end of the file if opened as Append.
                if (_mode == FileMode.Append)
                {
                    _appendStart = SeekCore(0, SeekOrigin.End);
                }
            }
            catch
            {
                // If anything goes wrong while setting up the stream, make sure we deterministically dispose
                // of the opened handle.
                _fileHandle.Dispose();
                _fileHandle = null;
                throw;
            }
        }
示例#58
0
 public static NativeFileOptions ToNative(this FileOptions fileOptions)
 {
     return((NativeFileOptions)(uint)fileOptions);
 }
示例#59
0
文件: File.cs 项目: jmhardison/corefx
 public static FileStream Create(String path, int bufferSize, FileOptions options)
 {
     return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
                           FileShare.None, bufferSize, options);
 }
示例#60
0
        private NtStatus Trace(string method, string fileName, DokanFileInfo info, FileAccess access, FileShare share, FileMode mode, FileOptions options, FileAttributes attributes, NtStatus result)
        {
            logger?.Trace($"{System.Threading.Thread.CurrentThread.ManagedThreadId:D2} / {drive.DisplayRoot} {method}({fileName}, {info.ToTrace()}, [{access}], [{share}], [{mode}], [{options}], [{attributes}]) -> {result}".ToString(CultureInfo.CurrentCulture));

            return(result);
        }