Exemplo n.º 1
0
        /// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlTypes/SqlFileStream.xml' path='docs/members[@name="SqlFileStream"]/ctor2/*' />
        public SqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            IntPtr hscp;

            Bid.ScopeEnter(out hscp, "<sc.SqlFileStream.ctor|API> %d# access=%d options=%d path='%ls' ", ObjectID, (int)access, (int)options, path);

            try
            {
                //-----------------------------------------------------------------
                // 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
                this.Name = path;
                this.TransactionContext = transactionContext;
            }
            finally
            {
                Bid.ScopeLeave(ref hscp);
            }
        }
Exemplo n.º 2
0
        /// <include file='../../../../../../../doc/snippets/Microsoft.Data.SqlTypes/SqlFileStream.xml' path='docs/members[@name="SqlFileStream"]/ctor2/*' />
        public SqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            long scopeID = SqlClientEventSource.Log.TryScopeEnterEvent("<sc.SqlFileStream.ctor|API> {0} access={1} options={2} path='{3}'", ObjectID, (int)access, (int)options, path);

            try
            {
                //-----------------------------------------------------------------
                // 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
                this.Name = path;
                this.TransactionContext = transactionContext;
            }
            finally
            {
                SqlClientEventSource.Log.TryScopeLeaveEvent(scopeID);
            }
        }
Exemplo n.º 3
0
        public NtStatus CreateFile(string filename, FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, System.IO.FileAttributes attributes, DokanFileInfo info)
        {
            var node = GetNodeFast(filename, info);

            if (node == null)
            {
                if (access == FileAccess.Delete)
                {
                    return(DokanResult.Success);                            //already gone
                }
                switch (mode)
                {
                case FileMode.CreateNew:
                case FileMode.Create:
                case FileMode.OpenOrCreate:
                    if (filename.Length == 0)
                    {
                        return(NtStatus.Success);
                    }
                    string Directory = filename;
                    if (!info.IsDirectory)     //Directory doesn't have a filename that we want to cut off
                    {
                        Directory = filename.Substring(0, filename.LastIndexOf('\\'));
                        if (Directory.Length == 0)
                        {
                            Directory = "\\";
                        }
                    }


                    var nodeDirectory = CreateOrFindDirectoryRecursive(Directory);

                    if (!(nodeDirectory is PboFsRealFolder) && nodeDirectory is PboFsFolder virtualFolder)
                    {
                        nodeDirectory = fileTree.MakeDirectoryWriteable(virtualFolder);
                    }

                    if (nodeDirectory is PboFsRealFolder folder)
                    {
                        if (info.IsDirectory)
                        {
                            info.Context = nodeDirectory;
                            //Nothing else to do as full path is already included in DirectoryPath
                        }
                        else
                        {
                            //Filename without folder path
                            var FileNameDirect = filename.Substring(filename.LastIndexOf('\\'));
                            var FileNameDirectNoLeadingSlash = filename.Substring(filename.LastIndexOf('\\') + 1);

                            FileStream newStream = null;
                            try
                            {
                                newStream = System.IO.File.Create(folder.path + FileNameDirect);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                return(DokanResult.AccessDenied);   //#TODO correct result for exception type
                            }

                            var rlFile = new PboFsRealFile(new System.IO.FileInfo(folder.path + FileNameDirect), folder, newStream);

                            folder.Children[FileNameDirectNoLeadingSlash.ToLower()] = rlFile;
                            fileTree.AddNode(rlFile);
                            info.Context = rlFile;
                        }

                        return(DokanResult.Success);
                    }

                    return(DokanResult.DiskFull);

                case FileMode.Open:
                case FileMode.Truncate:
                case FileMode.Append:
                    return(DokanResult.FileNotFound);
                }
            }

            info.Context = node;
            if (node is PboFsFolder && !info.IsDirectory)
            {
                info.IsDirectory = true;                                           //Dokan documentation says we need to do that.
            }
            if (mode == FileMode.CreateNew)
            {
                return(DokanResult.FileExists);
            }

            if (access == FileAccess.Delete)
            {
                NtStatus deleteResult = DokanResult.NotImplemented;
                if (node is PboFsRealFile)
                {
                    deleteResult = DeleteFile(filename, info);
                }
                else if (node is PboFsRealFolder)
                {
                    deleteResult = DeleteDirectory(filename, info);
                }

                return(deleteResult);
            }

            bool wantsWrite = (access &
                               (FileAccess.WriteData | FileAccess.AppendData | FileAccess.Delete | FileAccess.GenericWrite)
                               ) != 0;

            bool wantsRead = (access &
                              (FileAccess.ReadData | FileAccess.GenericRead | FileAccess.Execute | FileAccess.GenericExecute)
                              ) != 0;

            if (wantsWrite && !(node is IPboFsRealObject))
            {
                return(DokanResult.AccessDenied);
            }

            if (node is IPboFsFile file && (wantsRead || wantsWrite))
            {
                return(file.Open(wantsWrite, mode));
            }

            return(DokanResult.Success);
        }
Exemplo n.º 4
0
        public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, DokanFileInfo info)
        {
            int ret = DokanNet.DOKAN_SUCCESS;

            filename = CleanFileName(filename);

            try
            {
                Debug("CreateFile {0}", filename);

                string Directory = MainForm.In.mNFS.GetDirectoryName(filename);
                string FileName  = MainForm.In.mNFS.GetFileName(filename);
                string FullPath  = MainForm.In.mNFS.Combine(FileName, Directory);

                if (MainForm.In.mNFS.IsDirectory(FullPath))
                {
                    return(ret);
                }

                switch (mode)
                {
                case FileMode.Open:
                {
                    Debug("Open");
                    if (!MainForm.In.mNFS.FileExists(FullPath))
                    {
                        ret = -DokanNet.ERROR_FILE_NOT_FOUND;
                    }
                    break;
                }

                case FileMode.CreateNew:
                {
                    Debug("CreateNew");
                    if (MainForm.In.mNFS.FileExists(FullPath))
                    {
                        ret = -DokanNet.ERROR_ALREADY_EXISTS;
                    }
                    else
                    {
                        MainForm.In.mNFS.CreateFile(FullPath);
                    }
                    break;
                }

                case FileMode.Create:
                {
                    Debug("Create");
                    if (MainForm.In.mNFS.FileExists(FullPath))
                    {
                        MainForm.In.mNFS.DeleteFile(FullPath);
                    }

                    MainForm.In.mNFS.CreateFile(FullPath);
                    break;
                }

                case FileMode.OpenOrCreate:
                {
                    Debug("OpenOrCreate");
                    if (!MainForm.In.mNFS.FileExists(FullPath))
                    {
                        MainForm.In.mNFS.CreateFile(FullPath);
                    }
                    break;
                }

                case FileMode.Truncate:
                {
                    Debug("Truncate");
                    if (!MainForm.In.mNFS.FileExists(FullPath))
                    {
                        ret = -DokanNet.ERROR_FILE_NOT_FOUND;
                    }
                    else
                    {
                        MainForm.In.mNFS.CreateFile(FullPath);
                    }
                    break;
                }

                case FileMode.Append:
                {
                    Debug("Appen");
                    if (!MainForm.In.mNFS.FileExists(FullPath))
                    {
                        ret = -DokanNet.ERROR_FILE_NOT_FOUND;
                    }
                    break;
                }

                default:
                {
                    Debug("Error unknown FileMode {0}", mode);
                    break;
                }
                }
            }
            catch (Exception ex)
            {
                ret = -DokanNet.DOKAN_ERROR;
                Debug("CreateFile file {0} exception {1}", filename, ex.Message);
            }
            return(ret);
        }
Exemplo n.º 5
0
        public int CreateFile(
            string filename,
            System.IO.FileAccess access,
            System.IO.FileShare share,
            System.IO.FileMode mode,
            System.IO.FileOptions options,
            DokanFileInfo info)
        {
            Console.WriteLine("Dokan CreateFile, filename is " + filename);
            Dokan.DokanNet.DokanResetTimeout(1000 * 30, info);
            info.Context = Context++;
            string targetPath = filename.Replace("\\", "/");
            String name       = GetFileName(targetPath);

            #region 老方法 - 废弃,参考
            //try
            //{
            //    if (filename == "\\")
            //    {

            //        //info.IsDirectory = true;
            //        return DokanNet.DOKAN_SUCCESS;

            //    }


            //    if (name == "desktop.ini" || name == "folder.jpg" || name == "folder.gif" || name == @".svn") return -DokanNet.ERROR_FILE_NOT_FOUND;



            //    #region 通过List<FileElement>查询文件
            //    FileElement file = allinone.getSingleFileInfo(targetPath);
            //    if (file == null)
            //    {

            //    }

            //    else if ((access & System.IO.FileAccess.Read) == System.IO.FileAccess.Read)
            //    {


            //        if (file.isdir == System.IO.FileAttributes.Directory)
            //        {
            //            info.IsDirectory = true;
            //            return DokanNet.DOKAN_SUCCESS;
            //        }
            //        else
            //        {
            //            return DokanNet.DOKAN_SUCCESS;
            //        }

            //    }

            //    #endregion

            //    #region Mem盘的方法  - 废弃
            //    //FileElement file = allinone.getSingleFileInfo(targetPath);
            //    //if (file!=null)
            //    //{
            //    //    //this is a folder?
            //    //    info.IsDirectory = true;
            //    //    if (mode == FileMode.Open || mode == FileMode.OpenOrCreate)
            //    //    {
            //    //        //info.IsDirectory = true;
            //    //        return DokanNet.DOKAN_SUCCESS;
            //    //    }

            //    //    // you can't make a file with the same name as a folder;
            //    //    return -DokanNet.ERROR_ALREADY_EXISTS;
            //    //}
            //    #endregion
            //    // there's no folder with this name, the parent exists;
            //    // attempt to use the file
            //    switch (mode)
            //    {
            //        // Opens the file if it exists and seeks to the end of the file,
            //        // or creates a new file
            //        case FileMode.Append:

            //            return DokanNet.DOKAN_SUCCESS;

            //        // Specifies that the operating system should create a new file.
            //        // If the file already exists, it will be overwritten.
            //        case FileMode.Create:
            //            //if (!thisFile.Exists())

            //            //else
            //            //	thisFile.Content = new Thought.Research.AweBuffer(1024); //MemoryStream();
            //            return DokanNet.DOKAN_SUCCESS;

            //        // Specifies that the operating system should create a new file.
            //        // If the file already exists, an IOException is thrown.
            //        case FileMode.CreateNew:
            //            Console.WriteLine("try to create new file, file name is " + name);
            //            return DokanNet.DOKAN_SUCCESS;

            //        // Specifies that the operating system should open an existing file.
            //        // A System.IO.FileNotFoundException is thrown if the file does not exist.
            //        case FileMode.Open:

            //            return DokanNet.DOKAN_SUCCESS;

            //        // Specifies that the operating system should open a file if it exists;
            //        // otherwise, a new file should be created.
            //        case FileMode.OpenOrCreate:

            //            return DokanNet.DOKAN_SUCCESS;

            //        // Specifies that the operating system should open an existing file.
            //        // Once opened, the file should be truncated so that its size is zero bytes
            //        case FileMode.Truncate:


            //            return DokanNet.DOKAN_SUCCESS;
            //    }



            //}
            //catch (Exception e)
            //{
            //    Console.WriteLine(e);
            //}

            //return DokanNet.DOKAN_SUCCESS;

            #endregion

            #region 13/11/1添加改用新方法

            if (filename == "\\")
            {
                //info.IsDirectory = true;
                return(DokanNet.DOKAN_SUCCESS);
            }

            if (mode == FileMode.Open || mode == FileMode.OpenOrCreate)
            {
                FileElement file = allinone.getSingleFileInfo(targetPath);
                if (file != null)
                {
                    if (file.isdir == System.IO.FileAttributes.Normal)
                    {
                        return(DokanNet.DOKAN_SUCCESS);
                    }

                    if (file.isdir == System.IO.FileAttributes.Directory)
                    {
                        info.IsDirectory = true;
                        return(DokanNet.DOKAN_SUCCESS);
                    }
                }

                return(-DokanNet.ERROR_FILE_NOT_FOUND);
            }

            return(DokanNet.DOKAN_SUCCESS);

            #endregion
        }
Exemplo n.º 6
0
        private void OpenSqlFileStream
        (
            string path,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            Int64 allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation

            // these should be checked by any caller of this method

            // ensure we have validated and normalized the path before
            Debug.Assert(path != null);
            Debug.Assert(transactionContext != null);

            if (access != FileAccess.Read && access != FileAccess.Write && access != FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

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

            // normalize the provided path
            //   * compress path to remove any occurences of '.' or '..'
            //   * trim whitespace from the beginning and end of the path
            //   * ensure that the path starts with '\\'
            //   * ensure that the path does not start with '\\.\'
            //   * ensure that the path is not longer than Int16.MaxValue
            path = GetFullPathInternal(path);

            // ensure the running code has permission to read/write the file
            DemandAccessPermission(path, access);

            FileFullEaInformation    eaBuffer   = null;
            SecurityQualityOfService qos        = null;
            UnicodeString            objectName = null;

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile = null;

            int nDesiredAccess = UnsafeNativeMethods.FILE_READ_ATTRIBUTES | UnsafeNativeMethods.SYNCHRONIZE;

            UInt32 dwCreateOptions     = 0;
            UInt32 dwCreateDisposition = 0;

            System.IO.FileShare shareAccess = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= UnsafeNativeMethods.FILE_READ_DATA | UnsafeNativeMethods.FILE_WRITE_DATA;
                shareAccess         = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = (uint)UnsafeNativeMethods.CreationDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= (uint)UnsafeNativeMethods.CreateOption.FILE_RANDOM_ACCESS;
            }

            try
            {
                eaBuffer = new FileFullEaInformation(transactionContext);

                qos = new SecurityQualityOfService(UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous,
                                                   false, false);

                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                //   FILESTREAM attributed column data. We will not surface the internal processing that
                //   takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(path);
                objectName = new UnicodeString(mappedPath);

                UnsafeNativeMethods.OBJECT_ATTRIBUTES oa;
                oa.length                   = Marshal.SizeOf(typeof(UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                oa.rootDirectory            = IntPtr.Zero;
                oa.attributes               = (int)UnsafeNativeMethods.Attributes.CaseInsensitive;
                oa.securityDescriptor       = IntPtr.Zero;
                oa.securityQualityOfService = qos;
                oa.objectName               = objectName;

                UnsafeNativeMethods.IO_STATUS_BLOCK ioStatusBlock;

                uint oldMode;
                uint retval = 0;

                UnsafeNativeMethods.SetErrorModeWrapper(UnsafeNativeMethods.SEM_FAILCRITICALERRORS, out oldMode);
                try
                {
                    Bid.Trace("<sc.SqlFileStream.OpenSqlFileStream|ADV> %d#, desiredAccess=0x%08x, allocationSize=%I64d, fileAttributes=0x%08x, shareAccess=0x%08x, dwCreateDisposition=0x%08x, createOptions=0x%08x\n",
                              ObjectID, (int)nDesiredAccess, allocationSize, 0, (int)shareAccess, dwCreateDisposition, dwCreateOptions);

                    retval = UnsafeNativeMethods.NtCreateFile(out hFile, nDesiredAccess,
                                                              ref oa, out ioStatusBlock, ref allocationSize,
                                                              0, shareAccess, dwCreateDisposition, dwCreateOptions,
                                                              eaBuffer, (uint)eaBuffer.Length);
                }
                finally
                {
                    UnsafeNativeMethods.SetErrorModeWrapper(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case UnsafeNativeMethods.STATUS_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(Res.GetString(Res.SqlFileStream_FileAlreadyInTransaction));

                case UnsafeNativeMethods.STATUS_INVALID_PARAMETER:
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_InvalidParameter));

                case UnsafeNativeMethods.STATUS_OBJECT_NAME_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = UnsafeNativeMethods.RtlNtStatusToDosError(retval);
                    if (error == UnsafeNativeMethods.ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(UnsafeNativeMethods.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                UnsafeNativeMethods.FileType fileType = UnsafeNativeMethods.GetFileType(hFile);
                if (fileType != UnsafeNativeMethods.FileType.Disk)
                {
                    hFile.Dispose();
                    throw ADP.Argument(Res.GetString(Res.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                //   through current data and then append new data to the end, so we need to tell SQL Server to preserve
                //   the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = UnsafeNativeMethods.CTL_CODE(UnsafeNativeMethods.FILE_DEVICE_FILE_SYSTEM,
                                                                      IoControlCodeFunctionCode, (byte)UnsafeNativeMethods.Method.METHOD_BUFFERED,
                                                                      (byte)UnsafeNativeMethods.Access.FILE_ANY_ACCESS);
                    uint cbBytesReturned = 0;

                    if (!UnsafeNativeMethods.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                //   use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                // NOTE: need to assert UnmanagedCode permissions for this constructor. This is relatively benign
                //   in that we've done much the same validation as in the FileStream(string path, ...) ctor case
                //   most notably, validating that the handle type corresponds to an on-disk file.
                bool bRevertAssert = false;
                try
                {
                    SecurityPermission sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode);
                    sp.Assert();
                    bRevertAssert = true;

                    System.Diagnostics.Debug.Assert(m_fs == null);
                    m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
                }
                finally
                {
                    if (bRevertAssert)
                    {
                        SecurityPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }

                if (qos != null)
                {
                    qos.Dispose();
                    qos = null;
                }

                if (objectName != null)
                {
                    objectName.Dispose();
                    objectName = null;
                }
            }
        }
Exemplo n.º 7
0
 public abstract DokanError CreateFile(string fileName, FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, System.IO.FileAttributes attributes, DokanFileInfo info);
Exemplo n.º 8
0
 public static SIO.FileStream Create(Hierarchy hierarchy, int bufferSize, SIO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity, string fn, params string[] fns)
 {
     throw new NotImplementedException("KSPe.IO.File.Create");
 }
Exemplo n.º 9
0
 /// <summary>
 ///     Opens the specified file.
 /// </summary>
 /// <param name="path">
 ///     A <see cref="String"/> containing the path of the file to open.
 /// </param>
 /// <param name="access">
 ///     One of the <see cref="FileAccess"/> value that specifies the operations that can be
 ///     performed on the file.
 /// </param>
 /// <param name="mode">
 ///     One of the <see cref="FileMode"/> values that specifies whether a file is created
 ///     if one does not exist, and determines whether the contents of existing files are
 ///     retained or overwritten.
 /// </param>
 /// <param name="share">
 ///     One of the <see cref="FileShare"/> values specifying the type of access other threads
 ///     have to the file.
 /// </param>
 /// <param name="bufferSize">
 ///     An <see cref="Int32"/> containing the number of bytes to buffer for reads and writes
 ///     to the file, or 0 to specified the default buffer size, 1024.
 /// </param>
 /// <param name="options">
 ///     One or more of the <see cref="FileOptions"/> values that describes how to create or
 ///     overwrite the file.
 /// </param>
 /// <returns>
 ///     A <see cref="FileStream"/> that provides access to the file specified in
 ///     <paramref name="path"/>.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 ///     <paramref name="path"/> is <see langword="null"/>.
 /// </exception>
 /// <exception cref="ArgumentException">
 ///     <paramref name="path"/> is an empty string (""), contains only white
 ///     space, or contains one or more invalid characters as defined in
 ///     <see cref="Path.GetInvalidPathChars()"/>.
 ///     <para>
 ///         -or-
 ///     </para>
 ///     <paramref name="path"/> contains one or more components that exceed
 ///     the drive-defined maximum length. For example, on Windows-based
 ///     platforms, components must not exceed 255 characters.
 /// </exception>
 /// <exception cref="ArgumentOutOfRangeException">
 ///     <paramref name="bufferSize"/> is less than 0.
 /// </exception>
 /// <exception cref="PathTooLongException">
 ///     <paramref name="path"/> exceeds the system-defined maximum length.
 ///     For example, on Windows-based platforms, paths must not exceed
 ///     255 characters.
 /// </exception>
 /// <exception cref="DirectoryNotFoundException">
 ///     One or more directories in <paramref name="path"/> could not be found.
 /// </exception>
 /// <exception cref="UnauthorizedAccessException">
 ///     The caller does not have the required access permissions.
 ///     <para>
 ///         -or-
 ///     </para>
 ///     <paramref name="path"/> refers to a file that is read-only and <paramref name="access"/>
 ///     is not <see cref="FileAccess.Read"/>.
 ///     <para>
 ///         -or-
 ///     </para>
 ///     <paramref name="path"/> is a directory.
 /// </exception>
 /// <exception cref="IOException">
 ///     <paramref name="path"/> refers to a file that is in use.
 ///     <para>
 ///         -or-
 ///     </para>
 ///     <paramref name="path"/> specifies a device that is not ready.
 /// </exception>
 public System.IO.FileStream Open(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options)
 {
     return(new FileStream(path, mode, access, share, bufferSize, options));
 }
Exemplo n.º 10
0
        /// <summary>
        ///		<see cref="IFileProvider.Open"/>
        /// </summary>
        public System.IO.FileStream Open(
            string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, int bufferSize, System.IO.FileOptions options)
        {
            if (bufferSize == 0)
            {
                bufferSize = 1024;
            }

            var longPath = new LongPath(path);

            SafeFileHandle handle = GetFileHandle(longPath, mode, access, share, options);

            return(new FileStream(handle, access, bufferSize, (options & FileOptions.Asynchronous) == FileOptions.Asynchronous));
        }
Exemplo n.º 11
0
        public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, DokanFileInfo info)
        {
            if (KeepStats)
            {
                Stats.count();
            }
            debug("...create file request for " + filename + " with access " + access + " with mode " + mode);
            if (filename.Equals(ROOT_PATH))
            {
                return(0);
            }
            else if (filename.StartsWith("\\autorun", StringComparison.CurrentCultureIgnoreCase))
            {
                return(0);
            }
            else if (filename.StartsWith(ROOT_PATH) && MySubDirs.ContainsKey(filename.Substring(1)))
            {
                List <Chunk> lst;
                MySubDirs.TryGetValue(filename.Substring(1), out lst);
                info.Context = (ulong)this.getNextId();
                openChunks.Add((ulong)info.Context, new OpenChunk(filename.Substring(1), lst));
                return(0);
            }
            string fn = (filename.StartsWith("\\")) ? filename.Substring(filename.LastIndexOf("\\") + 1) : filename;

            if (this.MyDirectory.ContainsKey(fn))
            {
                if (mode != FileMode.Open)
                {
                    return(-1);
                }
                if (access != FileAccess.Read)
                {
                    return(-1);
                }
                Chunk c;
                MyDirectory.TryGetValue(fn, out c);

                info.Context = (ulong)this.getNextId();
                debug("...create file request ****CTX*** is " + (ulong)info.Context);
                //FileStream fs = File.Open(c.ActualPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                FileStream fs = new FileStream(c.ActualPath, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, FileOptions.SequentialScan);
                openChunks.Add((ulong)info.Context, new OpenChunk(c, fs));
                return(0);
            }
            else
            {
                return(0);
            }
        }
Exemplo n.º 12
0
 public System.IO.FileStream Create(string subpath, int bufferSize, System.IO.FileOptions options, System.Security.AccessControl.FileSecurity fileSecurity)
 {
     return(File.Create(Path.Combine(RootDir, subpath), bufferSize, options, fileSecurity));
 }
Exemplo n.º 13
0
 public System.IO.FileStream Create(string subpath, int bufferSize, System.IO.FileOptions options)
 {
     return(File.Create(Path.Combine(RootDir, subpath), bufferSize, options));
 }
Exemplo n.º 14
0
 /// <summary>
 /// Converts a <strong>System.IO.FileOptions</strong> value to 
 /// <strong>DigitalRune.Storages.FileOptions</strong>.
 /// </summary>
 /// <param name="value">The <strong>System.IO.FileOptions</strong> value.</param>
 /// <returns>The <strong>DigitalRune.Storages.FileOptions</strong> value.</returns>
 public static FileOptions FromSystemIO(System.IO.FileOptions value)
 {
   return (FileOptions)value;
 }
 public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, Dokan.DokanFileInfo info)
 {
     try
     {
         info.Context = FileSystem.OpenFile(filename, mode);
         return(0);
     }
     catch (Exception e)
     {
         Console.WriteLine(" -- CreateFile Error: " + e.Message);
         info.Context = null;
         //return -1;
         return(0);
     }
     finally
     {
         NotImplemented(filename, info.Context);
     }
     //info.Context = FileSystem.OpenFile(filename, mode);
 }
Exemplo n.º 16
0
 public static SIO.FileStream Create(Hierarchy hierarchy, int bufferSize, SIO.FileOptions options, string fn, params string[] fns)
 {
     throw new NotImplementedException("KSPe.IO.File.Create");
 }
Exemplo n.º 17
0
        public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, DokanFileInfo info)
        {
            FileInformation fi = new FileInformation();

            GetFileInformation(filename, ref fi, info);

            switch (mode)
            {
            case FileMode.Append:
                return(DokanNet.DOKAN_SUCCESS);

            case FileMode.Create:
                AddToFileCache(filename, FillFileCache(filename));
                return(DokanNet.DOKAN_SUCCESS);

            case FileMode.CreateNew:
                AddToFileCache(filename, FillFileCache(filename));
                return(DokanNet.DOKAN_SUCCESS);

            case FileMode.Open:
                return(DokanNet.DOKAN_SUCCESS);

            case FileMode.Truncate:
                return(DokanNet.DOKAN_SUCCESS);
            }
            return(DokanNet.DOKAN_ERROR);
        }
Exemplo n.º 18
0
        //Windows System Error Codes @ http://www.hiteksoftware.com/knowledge/articles/049.htm
        public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, DokanFileInfo info)
        {
            Console.WriteLine("crFile: " + filename);

            info.Context = count++;

            if (filename.Trim() == "\\")
            {
                info.IsDirectory = true;
                return(0);
            }
            else
            {
                RAFInMemoryFileSystemObject fso = rafManager.ResolveRAFPathTOFSO(filename);
                Console.WriteLine("-> FSO NULL? " + (fso == null));
                if (fso == null)
                {
                    return(-DokanNet.ERROR_ACCESS_DENIED);
                }
                else
                {
                    if (fso.GetFSOType() == RAFFSOType.DIRECTORY)
                    {
                        info.IsDirectory = true;
                    }
                    return(0);
                }
            }
            //return -82;
        }
Exemplo n.º 19
0
    private bool IsFileInUse(System.IO.FileShare fshare = FileShare.Read, System.Security.AccessControl.FileSystemRights fSysRights = FileSystemRights.Read, System.IO.FileAccess fAccess = FileAccess.Read, System.IO.FileMode fMode = FileMode.Open, System.IO.FileOptions fOptions = FileOptions.None)
    {
        bool inUse = false;


        try
        {
            do
            {
                this.m_fileHandle = CreateFile(this.m_path, fSysRights, fshare, IntPtr.Zero, fMode, FileOptions.None, IntPtr.Zero);

                if (this.m_fileHandle.IsInvalid)
                {
                    int LastErr = Marshal.GetLastWin32Error();
                    //Console.WriteLine("IsFileInUse LastErr: " & LastErr & ", " & New Win32Exception(LastErr).Message, , , False)
                    inUse = true;
                    if (LastErr == ERROR_SHARING_VIOLATION || LastErr == ERROR_LOCK_VIOLATION)
                    {
                        if (!this.m_fileHandle.IsClosed)
                        {
                            this.m_fileHandle.Close();
                        }
                    }
                    else
                    {
                        //Me.m_fileStream = New FileStream(m_fileHandle, fAccess)
                    }
                }
                else
                {
                    this.m_fileStream = new FileStream(this.m_fileHandle, fAccess);
                }
                break;
            } while (true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("IsFileInUse Error: " + ex.Msg());
            inUse = true;
        }
        finally
        {
        }

        return(inUse);
    }
Exemplo n.º 20
0
        public uint Def_CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, IntPtr info)
        {
            //return 0;
            RegistryFileBlock rb = new RegistryFileBlock(filename);

            if (rb.ValueKind > 0)
            {
                if (mode == FileMode.CreateNew || mode == FileMode.OpenOrCreate)
                {
                    if (rb.level == 2)
                    {
                        GetRegistoryEntry(rb).CreateSubKey(rb.KeyPointer.Substring(rb.KeyPointer.LastIndexOf("\\") + 1));
                        return(0);
                    }
                    int check;

                    if (rb.level == 3 && filename.EndsWith(regtypes[rb.ValueKind], StringComparison.CurrentCultureIgnoreCase))
                    {
                        switch (rb.ValueKind)
                        {
                        case 1:
                            GetRegistoryEntry(rb).SetValue(rb.ValueName, 0, RegValueType[rb.ValueKind]);
                            break;

                        case 2:
                            GetRegistoryEntry(rb).SetValue(rb.ValueName, "", RegValueType[rb.ValueKind]);
                            break;

                        case 3:
                            GetRegistoryEntry(rb).SetValue(rb.ValueName, 0, RegValueType[rb.ValueKind]);
                            break;

                        case 4:
                            GetRegistoryEntry(rb).SetValue(rb.ValueName, "", RegValueType[rb.ValueKind]);
                            break;

                        default:
                            return(0xC000000F);
                        }
                        return(0);
                    }
                }
            }
            else
            {
                if (filename == "\\")
                {
                    return(0);
                }
                if (filename.EndsWith("dekstop.ini", StringComparison.CurrentCultureIgnoreCase) || filename.EndsWith("autorun.inf", StringComparison.CurrentCultureIgnoreCase))
                {
                    return(0);
                }
                // else
                // Console.WriteLine("Invalid New File {0}",filename);
                return(0xC000000F);
            }
            return(0xC000000F);
        }
Exemplo n.º 21
0
    private async Task <bool> LockFile(System.IO.FileShare fshare = FileShare.Read, System.Security.AccessControl.FileSystemRights fSysRights = FileSystemRights.Read, System.IO.FileAccess fAccess = FileAccess.Read, System.IO.FileMode fMode = FileMode.Open, System.IO.FileOptions fOptions = FileOptions.None)
    {
        int       num  = 0;
        bool      flag = false;
        Stopwatch SW   = new Stopwatch();

        SW.Start();
        while (!flag && (num < 2000) && (SW.ElapsedMilliseconds < 30000))
        {
            //Try
            if (!this.IsFileInUse(fshare, fSysRights, fAccess, fMode, fOptions))
            {
                if (fMode == FileMode.OpenOrCreate || fAccess == FileAccess.ReadWrite || fAccess == FileAccess.Write)
                {
                    try
                    {
                        this.m_fileStream.Lock(this.m_fileStream.Length, 0xFFFF);
                        this.m_WasLocked = true;
                        this.FileExists  = true;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("  LockFile Error: " + ex.Message);
                    }
                }
            }
            else
            {
                num += 1;
                await Task.Delay(10); //'Thread.Sleep(10)

                continue;
            }
            //Catch exception1 As Exception
            //    num += 1
            //    Thread.Sleep(10)
            //    Continue Do
            //End Try
            flag = true;
        }
        SW.Stop();
        if (num > 0)
        {
            Console.WriteLine("  Lockfile lock time: " + SW.ElapsedMilliseconds + "ms, errcount=" + num);
        }

        return(flag);
    }
Exemplo n.º 22
0
        private unsafe void OpenSqlFileStream
        (
            string sPath,
            byte[] transactionContext,
            System.IO.FileAccess access,
            System.IO.FileOptions options,
            long allocationSize
        )
        {
            //-----------------------------------------------------------------
            // precondition validation
            // these should be checked by any caller of this method
            // ensure we have validated and normalized the path before
            Debug.Assert(sPath != null);
            Debug.Assert(transactionContext != null);

            if (access != System.IO.FileAccess.Read && access != System.IO.FileAccess.Write && access != System.IO.FileAccess.ReadWrite)
            {
                throw ADP.ArgumentOutOfRange("access");
            }

            // FileOptions is a set of flags, so AND the given value against the set of values we do not support
            if ((options & ~(System.IO.FileOptions.WriteThrough | System.IO.FileOptions.Asynchronous | System.IO.FileOptions.RandomAccess | System.IO.FileOptions.SequentialScan)) != 0)
            {
                throw ADP.ArgumentOutOfRange("options");
            }

            //-----------------------------------------------------------------
            // normalize the provided path
            // * compress path to remove any occurrences of '.' or '..'
            // * trim whitespace from the beginning and end of the path
            // * ensure that the path starts with '\\'
            // * ensure that the path does not start with '\\.\'
            sPath = GetFullPathInternal(sPath);

            Microsoft.Win32.SafeHandles.SafeFileHandle hFile    = null;
            Interop.NtDll.DesiredAccess     nDesiredAccess      = Interop.NtDll.DesiredAccess.FILE_READ_ATTRIBUTES | Interop.NtDll.DesiredAccess.SYNCHRONIZE;
            Interop.NtDll.CreateOptions     dwCreateOptions     = 0;
            Interop.NtDll.CreateDisposition dwCreateDisposition = 0;
            System.IO.FileShare             nShareAccess        = System.IO.FileShare.None;

            switch (access)
            {
            case System.IO.FileAccess.Read:

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.ReadWrite;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OPEN;
                break;

            case System.IO.FileAccess.Write:
                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;

            case System.IO.FileAccess.ReadWrite:
            default:
                // we validate the value of 'access' parameter in the beginning of this method
                Debug.Assert(access == System.IO.FileAccess.ReadWrite);

                nDesiredAccess     |= Interop.NtDll.DesiredAccess.FILE_READ_DATA | Interop.NtDll.DesiredAccess.FILE_WRITE_DATA;
                nShareAccess        = System.IO.FileShare.Delete | System.IO.FileShare.Read;
                dwCreateDisposition = Interop.NtDll.CreateDisposition.FILE_OVERWRITE;
                break;
            }

            if ((options & System.IO.FileOptions.WriteThrough) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH;
            }

            if ((options & System.IO.FileOptions.Asynchronous) == 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT;
            }

            if ((options & System.IO.FileOptions.SequentialScan) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY;
            }

            if ((options & System.IO.FileOptions.RandomAccess) != 0)
            {
                dwCreateOptions |= Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS;
            }

            try
            {
                // NOTE: the Name property is intended to reveal the publicly available moniker for the
                // FILESTREAM attributed column data. We will not surface the internal processing that
                // takes place to create the mappedPath.
                string mappedPath = InitializeNtPath(sPath);
                int    retval     = 0;
                Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out uint oldMode);

                try
                {
                    if (transactionContext.Length >= ushort.MaxValue)
                    {
                        throw ADP.ArgumentOutOfRange("transactionContext");
                    }

                    int headerSize = sizeof(Interop.NtDll.FILE_FULL_EA_INFORMATION);
                    int fullSize   = headerSize + transactionContext.Length + s_eaNameString.Length;

                    byte[] buffer = ArrayPool <byte> .Shared.Rent(fullSize);

                    fixed(byte *b = buffer)
                    {
                        Interop.NtDll.FILE_FULL_EA_INFORMATION *ea = (Interop.NtDll.FILE_FULL_EA_INFORMATION *)b;
                        ea->NextEntryOffset = 0;
                        ea->Flags           = 0;
                        ea->EaNameLength    = (byte)(s_eaNameString.Length - 1); // Length does not include terminating null character.
                        ea->EaValueLength   = (ushort)transactionContext.Length;

                        // We could continue to do pointer math here, chose to use Span for convenience to
                        // make sure we get the other members in the right place.
                        Span <byte> data = buffer.AsSpan(headerSize);

                        s_eaNameString.AsSpan().CopyTo(data);
                        data = data.Slice(s_eaNameString.Length);
                        transactionContext.AsSpan().CopyTo(data);

                        (int status, IntPtr handle) = Interop.NtDll.CreateFile(
                            path: mappedPath.AsSpan(),
                            rootDirectory: IntPtr.Zero,
                            createDisposition: dwCreateDisposition,
                            desiredAccess: nDesiredAccess,
                            shareAccess: nShareAccess,
                            fileAttributes: 0,
                            createOptions: dwCreateOptions,
                            eaBuffer: b,
                            eaLength: (uint)fullSize);
                        retval = status;
                        hFile  = new SafeFileHandle(handle, true);
                    }

                    ArrayPool <byte> .Shared.Return(buffer);
                }
                finally
                {
                    Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
                }

                switch (retval)
                {
                case 0:
                    break;

                case Interop.Errors.ERROR_SHARING_VIOLATION:
                    throw ADP.InvalidOperation(System.SRHelper.GetString(SR.SqlFileStream_FileAlreadyInTransaction));

                case Interop.Errors.ERROR_INVALID_PARAMETER:
                    throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_InvalidParameter));

                case Interop.Errors.ERROR_FILE_NOT_FOUND:
                {
                    System.IO.DirectoryNotFoundException e = new System.IO.DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                default:
                {
                    uint error = Interop.NtDll.RtlNtStatusToDosError(retval);
                    if (error == ERROR_MR_MID_NOT_FOUND)
                    {
                        // status code could not be mapped to a Win32 error code
                        error = (uint)retval;
                    }

                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(unchecked ((int)error));
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }
                }

                if (hFile.IsInvalid)
                {
                    System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Interop.Errors.ERROR_INVALID_HANDLE);
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                if (Interop.Kernel32.GetFileType(hFile) != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
                {
                    hFile.Dispose();
                    throw ADP.Argument(System.SRHelper.GetString(SR.SqlFileStream_PathNotValidDiskResource));
                }

                // if the user is opening the SQL FileStream in read/write mode, we assume that they want to scan
                // through current data and then append new data to the end, so we need to tell SQL Server to preserve
                // the existing file contents.
                if (access == System.IO.FileAccess.ReadWrite)
                {
                    uint ioControlCode = Interop.Kernel32.CTL_CODE(FILE_DEVICE_FILE_SYSTEM,
                                                                   IoControlCodeFunctionCode, (byte)Interop.Kernel32.IoControlTransferType.METHOD_BUFFERED,
                                                                   (byte)Interop.Kernel32.IoControlCodeAccess.FILE_ANY_ACCESS);

                    if (!Interop.Kernel32.DeviceIoControl(hFile, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out uint cbBytesReturned, IntPtr.Zero))
                    {
                        System.ComponentModel.Win32Exception e = new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(e);
                        throw e;
                    }
                }

                // now that we've successfully opened a handle on the path and verified that it is a file,
                // use the SafeFileHandle to initialize our internal System.IO.FileStream instance
                System.Diagnostics.Debug.Assert(_m_fs == null);
                _m_fs = new System.IO.FileStream(hFile, access, DefaultBufferSize, ((options & System.IO.FileOptions.Asynchronous) != 0));
            }
            catch
            {
                if (hFile != null && !hFile.IsInvalid)
                {
                    hFile.Dispose();
                }

                throw;
            }
        }
Exemplo n.º 23
0
        public int CreateFile(string filename, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileMode mode, System.IO.FileOptions options, DokanFileInfo info)
        {
            string webFilename = Normalize(filename);

            Console.WriteLine("Open " + webFilename + " " + access);

            MemFileContext context = new MemFileContext();
            MemFile        file;

            context.Mode    = mode;
            context.Access  = access;
            context.Share   = share;
            context.Options = options;

            info.Context = context;

            switch (mode)
            {
            case FileMode.Append:
                if (!memfs.Exists(webFilename))
                {
                    return(-DokanNet.ERROR_FILE_NOT_FOUND);
                }

                file = memfs.Lookup(webFilename);

                break;

            case FileMode.Create:
                if (memfs.Exists(webFilename))
                {
                    if (!memfs.Delete(webFilename))
                    {
                        return(-DokanNet.ERROR_ACCESS_DENIED);
                    }
                }

                file = memfs.CreateFile(webFilename);

                break;

            case FileMode.CreateNew:


                if (memfs.Exists(webFilename))
                {
                    return(-DokanNet.ERROR_ALREADY_EXISTS);
                }

                file = memfs.CreateFile(webFilename);

                break;

            case FileMode.Open:
                if (memfs.Exists(webFilename))
                {
                    file = memfs.Lookup(webFilename);
                }
                else
                {
                    return(-DokanNet.ERROR_FILE_NOT_FOUND);
                }

                break;

            case FileMode.OpenOrCreate:

                if (!memfs.Exists(webFilename))
                {
                    file = memfs.CreateFile(webFilename);
                }
                else
                {
                    file = memfs.Lookup(webFilename);
                }

                break;

            case FileMode.Truncate:
                if (!memfs.Exists(webFilename))
                {
                    return(-DokanNet.ERROR_FILE_NOT_FOUND);
                }

                if (!memfs.Delete(webFilename))
                {
                    return(-DokanNet.ERROR_ACCESS_DENIED);
                }

                file = memfs.CreateFile(webFilename, 0);

                break;

            default:
                return(-1);
            }

            Console.WriteLine("Opened " + webFilename + " " + access + " about to lock");

            if (!file.TryLock())
            {
                Console.WriteLine("NOT NOT NOT " + webFilename + " " + access + " about to lock");
                return(DokanNet.ERROR_SHARING_VIOLATION);
            }



            file.LocallyModified = false;

            if (file.LastAccessed.AddMilliseconds(CacheMillis) < DateTime.Now)
            {
                if (File.Exists(memfs.LocalFilename(webFilename)))
                {
                    File.Delete(memfs.LocalFilename(webFilename));
                }
            }

            return(0);
        }