public MatrixTestCase(FileShare PreviousShare, FileAccess RequestedAccess, FileShare RequestedShare, bool ExpectSuccess)
 {
     previousShare = PreviousShare;
     requestedAccess = RequestedAccess;
     requestedShare = RequestedShare;
     expectSuccess = ExpectSuccess;
 }
		public virtual TextReader GetReader(out Encoding encoding, FileShare sharing)
		{
			string encodingName;
			StreamReader reader;

			var stream = this.GetInputStream(out encodingName, sharing);
			
			if (encodingName == null)
			{
				reader = new StreamReader(stream);
			}
			else
			{
				var enc = Encoding.GetEncoding(encodingName);

				if (enc != null)
				{
					reader = new StreamReader(stream, enc);
				}
				else
				{
					reader = new StreamReader(stream);
				}
			}

			encoding = reader.CurrentEncoding;

			return reader;
		}
	public FileStream(String path, FileMode mode,
					  FileAccess access, FileShare share,
					  int bufferSize)
			: this(path, mode, access, share, bufferSize, false)
			{
				// Nothing to do here.
			}
Example #4
0
 public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share)
 {
     if (mode != FileMode.Open || access != FileAccess.Read) {
         throw new IOException("can only read files from the XAP");
     }
     return OpenInputFileStream(path);
 }
Example #5
0
        public static void Lock(string path, int millisecondsTimeout, Action<FileStream> action,
            FileMode mode, FileAccess access, FileShare share)
        {
            var log = Program.Log;
            var autoResetEvent = new AutoResetEvent(false);

            const string pattern = "Lock('{0}', {1}, {2}, {3}, {4})";
            string msg = string.Format(pattern, path, millisecondsTimeout, mode, access, share);
            log.Trace(msg);

            while (true)
            {
                try
                {
                    using (var stream = File.Open(path, mode, access, share))
                    {
                        const string pattern2 = "Access to file: {0}, {1}, {2}, {3}";
                        string msg2 = string.Format(pattern2, path, mode, access, share);
                        log.Trace(msg2);

                        action(stream);
                        break;
                    }
                }
                catch (IOException exc)
                {
                    const string pattern3 = "Cannot access to file: {0}";
                    string msg3 = string.Format(pattern3, path);
                    log.TraceException(msg3, exc);

                    AutoResetFileSystemWatcher(path, millisecondsTimeout, autoResetEvent);
                }
            }
        }
Example #6
0
 public SeqFileStreamReader(string fn, FileMode mode, FileAccess access, FileShare share, int bufferSize)
     : base(fn, mode, access, share, bufferSize)
 {
     curfilename = fn;
     bufsz = bufferSize;
     _init();
 }
	public IsolatedStorageFileStream(String path, FileMode mode,
									 FileAccess access, FileShare share,
									 int bufferSize)
			: this(path, mode, access, share, bufferSize, null)
			{
				// Nothing to do here.
			}
        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;
            }
        }
Example #9
0
        public int CreateFile(String filename, FileAccess access, FileShare share,
            FileMode mode, FileOptions options, DokanFileInfo info)
        {
            string path = GetPath(filename);

            try
            {
                if (Directory.Exists(path))
                {
                    info.IsDirectory = true;
                }
                else
                {
                    FileStream fs = new FileStream(path, mode, access, share, 8, options);
                    fs.Close();
                }

                //Console.WriteLine("Create file: {0}\t access: {1}", filename, access);
                return DokanNet.DOKAN_SUCCESS;
            }
            catch (Exception e)
            {
                return -DokanNet.DOKAN_ERROR;
            }
        }
Example #10
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);
        }
Example #11
0
 private static extern SafeFileHandle CreateFile(string filename,
                                FileAccess desiredAccess,
                                FileShare shareMode,
                                IntPtr attributes,
                                FileMode creationDisposition,
                                uint flagsAndAttributes = 0,
                                IntPtr templateFile = default(IntPtr));
Example #12
0
		public Stream FileOpen(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
		{
#if WINDOWS_STORE_APP
			var folder = ApplicationData.Current.LocalFolder;
			if (fileMode == FileMode.Create || fileMode == FileMode.CreateNew)
			{
				return folder.OpenStreamForWriteAsync(filePath, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
			}
			else if (fileMode == FileMode.OpenOrCreate)
			{
				if (fileAccess == FileAccess.Read)
					return folder.OpenStreamForReadAsync(filePath).GetAwaiter().GetResult();
				else
				{
					// Not using OpenStreamForReadAsync because the stream position is placed at the end of the file, instead of the beginning
					var f = folder.CreateFileAsync(filePath, CreationCollisionOption.OpenIfExists).AsTask().GetAwaiter().GetResult();
					return f.OpenAsync(FileAccessMode.ReadWrite).AsTask().GetAwaiter().GetResult().AsStream();
				}
			}
			else if (fileMode == FileMode.Truncate)
			{
				return folder.OpenStreamForWriteAsync(filePath, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();
			}
			else
			{
				//if (fileMode == FileMode.Append)
				// Not using OpenStreamForReadAsync because the stream position is placed at the end of the file, instead of the beginning
				folder.CreateFileAsync(filePath, CreationCollisionOption.OpenIfExists).AsTask().GetAwaiter().GetResult().OpenAsync(FileAccessMode.ReadWrite).AsTask().GetAwaiter().GetResult().AsStream();
				var f = folder.CreateFileAsync(filePath, CreationCollisionOption.OpenIfExists).AsTask().GetAwaiter().GetResult();
				return f.OpenAsync(FileAccessMode.ReadWrite).AsTask().GetAwaiter().GetResult().AsStream();
			}
#else
			return File.Open(filePath, fileMode, fileAccess, fileShare);
#endif
		}
        /// <summary>
        /// File might be locked when attempting to open it. This will attempt to open the file the number of times specified by <paramref name="retry"/>
        /// </summary>
        /// <param name="filePath">The file to attempt to get a file stream for</param>
        /// <param name="retry">The number of times a file open should be attempted</param>
        /// <param name="fileMode">The file mode to use</param>
        /// <param name="fileAccess">The file access to use</param>
        /// <param name="fileShare">The file sharing to use</param>
        /// <returns>A file stream of the file</returns>
        /// <remarks>
        /// It attempt to open the file in increasingly longer periods and throw an exception if it cannot open it within the
        /// specified number of retries.
        /// </remarks>
        public Stream OpenFileStream(string filePath, int retry, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
        {
            var delay = 0;

            for(var i = 0; i < retry; i++)
            {
                try
                {
                    var stream = new FileStream(filePath, fileMode, fileAccess, fileShare);
                    return stream;
                }
                catch(DirectoryNotFoundException)
                {
                    CreateDirectoryStructure(filePath);
                }
                catch(FileNotFoundException)
                {
                    throw;
                }
                catch(IOException)
                {
                    delay += 100;
                    if(i == retry) throw;
                }
                Thread.Sleep(delay);
            }

            //We will never get here
            throw new IOException(string.Format("Unable to open file '{0}'", filePath));
        }
Example #14
0
        public static Stream CreateFile(
            string fileName, FileAccess fileAccess, FileShare fileShare, FileMode fileMode, FileAttributes flags)
        {
            // TODO: This is not quite right, but it's close.
            //
            var nativeAccess = fileAccess;
            if ((nativeAccess & FileAccess.Read) != 0)
            {
                nativeAccess &= ~FileAccess.Read;
                nativeAccess |= (FileAccess)GENERIC_READ;
            }
            if ((nativeAccess & FileAccess.Write) != 0)
            {
                nativeAccess &= ~FileAccess.Write;
                nativeAccess |= (FileAccess)GENERIC_WRITE;
            }

            var handle = _CreateFile(fileName, nativeAccess, fileShare, IntPtr.Zero, fileMode, flags, IntPtr.Zero);
            if (handle.IsInvalid)
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            return new SimpleFileStream(handle);
        }
Example #15
0
        /// <summary>
        /// Opens a <see cref="FileStream"/>
        /// </summary>
        /// <param name="pathInfo">The file to open. </param>
        /// <param name="mode"><see cref="FileMode"/> </param>
        /// <param name="access"><see cref="FileAccess"/></param>
        /// <param name="share"><see cref="FileShare"/></param>
        /// <returns><see cref="FileStream"/></returns>
        /// <remarks>http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx</remarks>
        public static FileStream Open( QuickIOPathInfo pathInfo, FileMode mode, FileAccess access, FileShare share )
        {
            Contract.Requires( pathInfo != null );
            Contract.Ensures( Contract.Result<FileStream>() != null );

            return OpenFileStream( pathInfo.FullNameUnc, access, mode, share );
        }
		static internal string ToString(string path, FileMode mode, FileAccess access, FileShare share)
		{
			// http://ee.php.net/fopen

			//'r'  	 Open for reading only; place the file pointer at the beginning of the file.
			//'r+' 	Open for reading and writing; place the file pointer at the beginning of the file.
			//'w' 	Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
			//'w+' 	Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
			//'a' 	Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
			//'a+' 	Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
			//'x' 	Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
			//'x+' 	Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. 

			if (mode == FileMode.OpenOrCreate)
			{
				if (access == FileAccess.Write)
				{
					if (File.Exists(path))
						return "r+b";
					else
						return "x+b";
				}

				if (access == FileAccess.Read)
				{
					if (File.Exists(path))
						return "rb";
					else
						return "xb";
				}
			}

			var e = new { mode, access, share };
			throw new NotImplementedException(e.ToString());
		}
Example #17
0
        /// <summary>
        /// Opens a <see cref="FileStream"/> 
        /// </summary>
        /// <param name="path">The file to open. </param>
        /// <param name="mode"><see cref="FileMode"/></param>
        /// <param name="access"><see cref="FileAccess"/></param>
        /// <param name="share"><see cref="FileShare"/> </param>
        /// <returns>A <see cref="FileStream"/></returns>
        /// <remarks>http://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx</remarks>
        public static FileStream Open( string path, FileMode mode, FileAccess access, FileShare share )
        {
            Contract.Requires( !String.IsNullOrWhiteSpace( path ) );
            Contract.Ensures( Contract.Result<FileStream>() != null );

            return OpenFileStream( path, access, mode, share );
        }
 internal LogStream(string path, int bufferSize, LogRetentionOption retention, long maxFileSize, int maxNumOfFiles)
 {
     string fullPath = Path.GetFullPath(path);
     this._fileName = fullPath;
     if (fullPath.StartsWith(@"\\.\", StringComparison.Ordinal))
     {
         throw new NotSupportedException(System.SR.GetString("NotSupported_IONonFileDevices"));
     }
     Microsoft.Win32.UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(FileShare.Read);
     int num = 0x100000;
     this._canWrite = true;
     this._pathSav = fullPath;
     this._fAccessSav = 0x40000000;
     this._shareSav = FileShare.Read;
     this._secAttrsSav = secAttrs;
     this._secAccessSav = FileIOPermissionAccess.Write;
     this._modeSav = (retention != LogRetentionOption.SingleFileUnboundedSize) ? FileMode.Create : FileMode.OpenOrCreate;
     this._flagsAndAttributesSav = num;
     this._seekToEndSav = retention == LogRetentionOption.SingleFileUnboundedSize;
     base.bufferSize = bufferSize;
     this._retention = retention;
     this._maxFileSize = maxFileSize;
     this._maxNumberOfFiles = maxNumOfFiles;
     this._Init(fullPath, this._fAccessSav, this._shareSav, this._secAttrsSav, this._secAccessSav, this._modeSav, this._flagsAndAttributesSav, this._seekToEndSav);
 }
        public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share)
        {
            //TODO: OpenInputFileStream with params

            Stream st = null;
            if (access == FileAccess.Read)
            {
                st = OpenInputFileStream(path);
                if (st == null)
                {
                    CRhoFile file = new CRhoFile();
                    file.open(path, CRhoFile.EOpenModes.OpenReadOnly);
                    st = file.getStream();
                }

            }
            else
            {
                CRhoFile file = new CRhoFile();
                file.open(path, CRhoFile.EOpenModes.OpenForReadWrite);
                st = file.getStream();
            }

            return st;
        }
        /// <summary>
        /// File might be locked when attempting to open it. This will attempt to open the file the number of times specified by <paramref name="retry"/>
        /// </summary>
        /// <param name="fileInfo">The file to attempt to get a file stream for</param>
        /// <param name="retry">The number of times a file open should be attempted</param>
        /// <param name="fileMode">The file mode to use</param>
        /// <param name="fileAccess">The file access to use</param>
        /// <param name="fileShare">The file sharing to use</param>
        /// <returns>A file stream of the file</returns>
        /// <remarks>
        /// It attempt to open the file in increasingly longer periods and throw an exception if it cannot open it within the
        /// specified number of retries.
        /// </remarks>
        public FileStream OpenFileStream(FileInfo fileInfo, int retry, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
        {
            var delay = 0;

            for (var i = 0; i < retry; i++)
            {
                try
                {
                    var stream = new FileStream(fileInfo.FullName, fileMode, fileAccess, fileShare);
                    return stream;
                }
                catch(FileNotFoundException)
                {
                    throw;
                }
                catch (IOException)
                {
                    delay += 100;
                    if (i == retry) throw;
                }

                Thread.Sleep(delay);
            }

            //We will never get here
            throw new IOException("Unable to open file - " + fileInfo.FullName);
        }
	public IsolatedStorageFileStream(String path, FileMode mode,
									 FileAccess access, FileShare share,
									 IsolatedStorageFile sf)
			: this(path, mode, access, share, BUFSIZ, sf)
			{
				// Nothing to do here.
			}
 private static extern IntPtr CreateFile(string fileName, 
     FILE_ACCESS_RIGHTS access,
     FileShare share,
     int securityAttributes,
     FileMode creation,
     FILE_FLAGS flags,
     IntPtr templateFile);
Example #23
0
 /// <summary>
 /// Check's if the file has the accessrights specified in the input parameters
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="fa">Read,Write,ReadWrite</param>
 /// <param name="fs">Read,ReadWrite...</param>
 /// <returns></returns>
 public static void CheckFileAccessRights(string fileName, FileMode fm, FileAccess fa, FileShare fs)
 {
   FileStream fileStream = null;
   StreamReader streamReader = null;
   try
   {
     Encoding fileEncoding = Encoding.Default;
     fileStream = File.Open(fileName, fm, fa, fs);
     streamReader = new StreamReader(fileStream, fileEncoding, true);
   }
   finally
   {
     try
     {
       if (fileStream != null)
       {
         fileStream.Close();
         fileStream.Dispose();
       }
       if (streamReader != null)
       {
         streamReader.Close();
         streamReader.Dispose();
       }
     }
     finally {}
   }
 }
 public static extern SafeFileHandle CreateFile(String fileName,
     FileAccess desiredAccess,
     FileShare shareMode,
     IntPtr securityAttrs,
     FileMode creationDisposition,
     int flagsAndAttributes,
     IntPtr templateFile);
Example #25
0
        /// <summary>
        /// Pass the file handle to the <see cref="System.IO.FileStream"/> constructor. 
        /// The <see cref="System.IO.FileStream"/> will close the handle.
        /// </summary>
        public static SafeFileHandle CreateFileHandle(
			string filePath,
			CreationDisposition creationDisposition,
			FileAccess fileAccess,
			FileShare fileShare)
        {
            filePath = CheckAddLongPathPrefix(filePath);

            // Create a file with generic write access
            var fileHandle =
                PInvokeHelper.CreateFile(
                    filePath,
                    fileAccess,
                    fileShare,
                    IntPtr.Zero,
                    creationDisposition,
                    0,
                    IntPtr.Zero);

            // Check for errors.
            var lastWin32Error = Marshal.GetLastWin32Error();
            if (fileHandle.IsInvalid)
            {
                throw new Win32Exception(
                    lastWin32Error,
                    string.Format(
                        "Error {0} creating file handle for file path '{1}': {2}",
                        lastWin32Error,
                        filePath,
                        CheckAddDotEnd(new Win32Exception(lastWin32Error).Message)));
            }

            // Pass the file handle to FileStream. FileStream will close the handle.
            return fileHandle;
        }
		public static FileStream OpenSequentialStream(string path, FileMode mode, FileAccess access, FileShare share)
		{
			var options = FileOptions.SequentialScan;

			if (concurrency > 0)
			{
				options |= FileOptions.Asynchronous;
			}

#if MONO
			return new FileStream( path, mode, access, share, bufferSize, options );
            #else
			if (unbuffered)
			{
				options |= NoBuffering;
			}
			else
			{
				return new FileStream(path, mode, access, share, bufferSize, options);
			}

			SafeFileHandle fileHandle = CreateFile(path, (int)access, share, IntPtr.Zero, mode, (int)options, IntPtr.Zero);

			if (fileHandle.IsInvalid)
			{
				throw new IOException();
			}

			return new UnbufferedFileStream(fileHandle, access, bufferSize, (concurrency > 0));
#endif
		}
Example #27
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);
        }
Example #28
0
        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;
        }
		private static extern SafeFileHandle CreateFile(
			string lpFileName,
			int dwDesiredAccess,
			FileShare dwShareMode,
			IntPtr securityAttrs,
			FileMode dwCreationDisposition,
			int dwFlagsAndAttributes,
			IntPtr hTemplateFile);
 // On NetFX FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access
 // to internals in CoreFX so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor.
 // (A path constructor would try and create the requested file and give us two open handles.)
 //
 // We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle
 // with ownsHandle: false avoids the parent class closing without our knowledge.
 private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitialiationData initializationData)
     : base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize)
 {
     _isf = initializationData.StorageFile;
     _givenPath = path;
     _fullPath = initializationData.FullPath;
     _fs = initializationData.NestedStream;
 }
 public override Stream OpenInputFileStream(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(OpenInputFileStream(path));
 }
        public static RowKeysPairAnsi GetInstanceFromRowKeysAnsi(string rowKeysAnsiFileName, ParallelOptions parallelOptions, FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.Read)
        {
            RowKeysPairAnsi rowKeysPairAnsi = new RowKeysPairAnsi();

            rowKeysPairAnsi.GetInstanceFromRowKeysStructFileNameInternal(rowKeysAnsiFileName, parallelOptions, fileAccess, fileShare);
            return(rowKeysPairAnsi);
        }
Example #33
0
        public IFileStream Open(string path, FileMode mode, FileAccess?access = null, FileShare share = FileShare.None)
        {
            Guard.NotNull(path, nameof(path));
            AssertPathIsNotEmpty(path);

            AbsolutePath absolutePath = owner.ToAbsolutePath(path);

            var handler   = new FileOpenHandler(container);
            var arguments = new FileOpenArguments(absolutePath, mode, access, FileOptions.None);

            return(handler.Handle(arguments));
        }
Example #34
0
        /// <summary>
        /// 从TXT文件反序列化
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="mode">指定操作系统打开文件的方式</param>
        /// <param name="access">定义用于控制对文件的读访问、写访问或读/写访问的常数</param>
        /// <param name="share">包含用于控制其他 System.IO.FileStream 对象对同一文件可以具有的访问类型的常数</param>
        /// <returns></returns>
        public static object DeserializationFromTxt(string path, FileMode mode, FileAccess access, FileShare share)
        {
            BinaryFormatter formatter      = new BinaryFormatter();
            FileStream      readFileStream = new FileStream(path, mode, access, share);
            object          temp           = (object)formatter.Deserialize(readFileStream);

            readFileStream.Close();
            return(temp);
        }
Example #35
0
 public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, IsolatedStorageFile?isf)
     : this(path, mode, access, share, DefaultBufferSize, isf)
 {
 }
Example #36
0
 public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile?isf)
     : this(path, mode, access, share, bufferSize, InitializeFileStream(path, mode, access, share, bufferSize, isf))
 {
 }
Example #37
0
        // If IsolatedStorageFile is null, then we default to using a file that is scoped by user, appdomain, and assembly.
        private static InitializationData InitializeFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile?isf)
        {
            ArgumentNullException.ThrowIfNull(path);

            if ((path.Length == 0) || path.Equals(BackSlash))
            {
                throw new ArgumentException(
                          SR.IsolatedStorage_Path);
            }

            bool createdStore = false;

            if (isf == null)
            {
                isf          = IsolatedStorageFile.GetUserStoreForDomain();
                createdStore = true;
            }

            if (isf.Disposed)
            {
                throw new ObjectDisposedException(null, SR.IsolatedStorage_StoreNotOpen);
            }

            switch (mode)
            {
            case FileMode.CreateNew:            // Assume new file
            case FileMode.Create:               // Check for New file & Unreserve
            case FileMode.OpenOrCreate:         // Check for new file
            case FileMode.Truncate:             // Unreserve old file size
            case FileMode.Append:               // Check for new file
            case FileMode.Open:                 // Open existing, else exception
                break;

            default:
                throw new ArgumentException(SR.IsolatedStorage_FileOpenMode);
            }

            InitializationData data = new InitializationData
            {
                FullPath    = isf.GetFullPath(path),
                StorageFile = isf
            };

            try
            {
                data.NestedStream = new FileStream(data.FullPath, mode, access, share, bufferSize, FileOptions.None);
            }
            catch (Exception e)
            {
                // Make an attempt to clean up the StorageFile if we created it
                try
                {
                    if (createdStore)
                    {
                        data.StorageFile?.Dispose();
                    }
                }
                catch
                {
                }

                // Exception message might leak the IsolatedStorage path. The .NET Framework prevented this by calling an
                // internal API which made sure that the exception message was scrubbed. However since the innerException
                // is never returned to the user(GetIsolatedStorageException() does not populate the innerexception
                // in retail bits we leak the path only under the debugger via IsolatedStorageException._underlyingException which
                // they can any way look at via IsolatedStorageFile instance as well.
                throw IsolatedStorageFile.GetIsolatedStorageException(SR.IsolatedStorage_Operation_ISFS, e);
            }

            return(data);
        }
Example #38
0
 /// <summary>Opens a file in the specified mode with read, write, or read/write access and the specified sharing option.</summary>
 /// <returns>A <see cref="T:System.IO.FileStream" /> object opened with the specified mode, access, and sharing options.</returns>
 /// <param name="mode">
 ///     A <see cref="T:System.IO.FileMode" /> constant specifying the mode (for example, Open or Append) in
 ///     which to open the file.
 /// </param>
 /// <param name="access">
 ///     A <see cref="T:System.IO.FileAccess" /> constant specifying whether to open the file with Read,
 ///     Write, or ReadWrite file access.
 /// </param>
 /// <param name="share">
 ///     A <see cref="T:System.IO.FileShare" /> constant specifying the type of access other FileStream
 ///     objects have to this file.
 /// </param>
 /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission. </exception>
 /// <exception cref="T:System.IO.FileNotFoundException">The file is not found. </exception>
 /// <exception cref="T:System.UnauthorizedAccessException">
 ///     The path is read-only or is a directory.
 /// </exception>
 /// <exception cref="T:System.IO.DirectoryNotFoundException">
 ///     The specified path is invalid, such as being on an unmapped
 ///     drive.
 /// </exception>
 /// <exception cref="T:System.IO.IOException">The file is already open. </exception>
 public Stream Open(FileMode mode, FileAccess access, FileShare share = FileShare.None)
 {
     return(FileSystem.OpenFile(Path, mode, access, share));
 }
Example #39
0
 public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share)
 {
     return(new FileStream(path, mode, access, share));
 }
Example #40
0
 /// <include file='../_Doc/mscorlib.xml' path='doc/members/member[@name="M:System.IO.FileStream.#ctor(System.String,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)"]/*' />
 public FileStream(string path, FileMode mode, FileAccess access, FileShare share)
 {
     throw new PlatformNotSupportedException("PCL");
 }
 internal virtual FileStream CreateFileStream(string filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
 {
     return(new FileStream(filePath, fileMode, fileAccess, fileShare));
 }
Example #42
0
        protected override Stream DoGetInputStream(string contentName, out string encoding, FileMode mode, FileShare sharing)
        {
            long length;

            return(WebFileSystem.DoGetInputStream(this, contentName, out encoding, mode, sharing, out creationDate, out exists, out length));
        }
Example #43
0
 private static Stream OpenFile(CodeContext /*!*/ context, PlatformAdaptationLayer pal, string name, FileMode fileMode, FileAccess fileAccess, FileShare fileShare)
 {
     try {
         return(pal.OpenInputFileStream(name, fileMode, fileAccess, fileShare));
     } catch (UnauthorizedAccessException e) {
         throw PythonFile.ToIoException(context, name, e);
     } catch (IOException e) {
         PythonFile.AddFilename(context, name, e);
         throw;
     }
 }
 public static Stream OpenForRead(this FileEntry self, FileMode fileMode = FileMode.Open,
                                  FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.Read)
 {
     return(self.Open(fileMode, fileAccess, fileShare));
 }
Example #45
0
 // On .NET Framework FileStream has an internal no arg constructor that we utilize to provide the facade. We don't have access
 // to internals in .NET Core so we'll do the next best thing and contort ourselves into the SafeFileHandle constructor.
 // (A path constructor would try and create the requested file and give us two open handles.)
 //
 // We only expose our own nested FileStream so the base class having a handle doesn't matter. Passing a new SafeFileHandle
 // with ownsHandle: false avoids the parent class closing without our knowledge.
 private IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, InitializationData initializationData)
     : base(new SafeFileHandle(initializationData.NestedStream.SafeFileHandle.DangerousGetHandle(), ownsHandle: false), access, bufferSize)
 {
     _isf       = initializationData.StorageFile;
     _givenPath = path;
     _fullPath  = initializationData.FullPath;
     _fs        = initializationData.NestedStream;
 }
 public static Stream OpenOrCreateForReadWrite(this FileEntry self, FileShare share = FileShare.Read)
 {
     return(self.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, share));
 }
Example #47
0
 public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
     : this(path, mode, access, share, bufferSize, null)
 {
 }
 public static object LoadAs(this FileEntry self, Type type, FileShare fileShare = FileShare.Read)
 {
     using (var selff = self.Open(FileMode.Open, FileAccess.Read, fileShare)) { return(selff.LoadAs(type)); }
 }
Example #49
0
 public override Stream openStream(String url, FileMode mode, FileAccess access, FileShare share)
 {
     return(zipFile.openFile(parseURLInZip(url)));
 }
 public static object LoadAs(this FileInfo self, Type t, FileShare fileShare = FileShare.Read)
 {
     using (FileStream s = File.Open(self.FullPath(), FileMode.Open, FileAccess.Read, fileShare)) { return(s.LoadAs(t)); }
 }
Example #51
0
        //注意:序列化需要在需序列化的对像前设置属性,如下所示
        //[Serializable]
        //private struct structTest { public byte one; public int two; public string three; }

        /// <summary>
        /// 序列化至TXT文件
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="source">序列化对象</param>
        /// <param name="mode">指定操作系统打开文件的方式</param>
        /// <param name="access">定义用于控制对文件的读访问、写访问或读/写访问的常数</param>
        /// <param name="share">包含用于控制其他 System.IO.FileStream 对象对同一文件可以具有的访问类型的常数</param>
        /// <returns></returns>
        public static void SerializeToTxt(string path, object source, FileMode mode, FileAccess access, FileShare share)
        {
            BinaryFormatter formatter       = new BinaryFormatter();
            FileStream      writeFileStream = new FileStream(path, mode, access, share);

            formatter.Serialize(writeFileStream, source);
            writeFileStream.Close();
        }
 public static T LoadAs <T>(this FileEntry self, FileShare fileShare = FileShare.Read)
 {
     using (Stream s = self.Open(FileMode.Open, FileAccess.Read, fileShare)) { return(s.LoadAs <T>()); }
 }
 public override Stream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(File.Open(path, mode, access, share));
 }
 public static T LoadAs <T>(this FileInfo self, FileShare fileShare = FileShare.Read)
 {
     using (FileStream s = self.LoadAsStream(fileShare: fileShare)) { return(s.LoadAs <T>()); }
 }
Example #55
0
 public Stream OpenFile(string path, FileAccess access = FileAccess.ReadWrite, FileShare share = FileShare.Read)
 {
     throw new System.NotImplementedException();
 }
 public static FileStream LoadAsStream(this FileInfo self, FileMode fileMode = FileMode.Open,
                                       FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.Read)
 {
     return(File.Open(self.FullPath(), fileMode, fileAccess, fileShare));
 }
        private void OpenSqlFileStream(string path, byte[] transactionContext, FileAccess access, FileOptions options, long allocationSize)
        {
            if (((access != FileAccess.Read) && (access != FileAccess.Write)) && (access != FileAccess.ReadWrite))
            {
                throw ADP.ArgumentOutOfRange("access");
            }
            if ((options & ~(FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.SequentialScan | FileOptions.WriteThrough)) != FileOptions.None)
            {
                throw ADP.ArgumentOutOfRange("options");
            }
            path = GetFullPathInternal(path);
            DemandAccessPermission(path, access);
            FileFullEaInformation    eaBuffer   = null;
            SecurityQualityOfService service    = null;
            UnicodeString            str        = null;
            SafeFileHandle           fileHandle = null;
            int       num2 = 0x100080;
            uint      num  = 0;
            uint      num4 = 0;
            FileShare none = FileShare.None;

            switch (access)
            {
            case FileAccess.Read:
                num2 |= 1;
                none  = FileShare.Delete | FileShare.ReadWrite;
                num4  = 1;
                break;

            case FileAccess.Write:
                num2 |= 2;
                none  = FileShare.Delete | FileShare.Read;
                num4  = 4;
                break;

            default:
                num2 |= 3;
                none  = FileShare.Delete | FileShare.Read;
                num4  = 4;
                break;
            }
            if ((options & (FileOptions.None | FileOptions.WriteThrough)) != FileOptions.None)
            {
                num |= 2;
            }
            if ((options & FileOptions.Asynchronous) == FileOptions.None)
            {
                num |= 0x20;
            }
            if ((options & FileOptions.SequentialScan) != FileOptions.None)
            {
                num |= 4;
            }
            if ((options & FileOptions.RandomAccess) != FileOptions.None)
            {
                num |= 0x800;
            }
            try
            {
                System.Data.SqlTypes.UnsafeNativeMethods.OBJECT_ATTRIBUTES object_attributes;
                eaBuffer = new FileFullEaInformation(transactionContext);
                service  = new SecurityQualityOfService(System.Data.SqlTypes.UnsafeNativeMethods.SecurityImpersonationLevel.SecurityAnonymous, false, false);
                str      = new UnicodeString(InitializeNtPath(path));
                object_attributes.length                   = Marshal.SizeOf(typeof(System.Data.SqlTypes.UnsafeNativeMethods.OBJECT_ATTRIBUTES));
                object_attributes.rootDirectory            = IntPtr.Zero;
                object_attributes.attributes               = 0x40;
                object_attributes.securityDescriptor       = IntPtr.Zero;
                object_attributes.securityQualityOfService = service;
                object_attributes.objectName               = str;
                uint mode   = System.Data.SqlTypes.UnsafeNativeMethods.SetErrorMode(1);
                uint status = 0;
                try
                {
                    System.Data.SqlTypes.UnsafeNativeMethods.IO_STATUS_BLOCK io_status_block;
                    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", this.ObjectID, num2, allocationSize, 0, (int)none, num4, num);
                    status = System.Data.SqlTypes.UnsafeNativeMethods.NtCreateFile(out fileHandle, num2, ref object_attributes, out io_status_block, ref allocationSize, 0, none, num4, num, eaBuffer, (uint)eaBuffer.Length);
                }
                finally
                {
                    System.Data.SqlTypes.UnsafeNativeMethods.SetErrorMode(mode);
                }
                switch (status)
                {
                case 0:
                    break;

                case 0xc000000d:
                    throw ADP.Argument(Res.GetString("SqlFileStream_InvalidParameter"));

                case 0xc0000034:
                {
                    DirectoryNotFoundException e = new DirectoryNotFoundException();
                    ADP.TraceExceptionAsReturnValue(e);
                    throw e;
                }

                case 0xc0000043:
                    throw ADP.InvalidOperation(Res.GetString("SqlFileStream_FileAlreadyInTransaction"));

                default:
                {
                    uint num6 = System.Data.SqlTypes.UnsafeNativeMethods.RtlNtStatusToDosError(status);
                    if (num6 == 0x13d)
                    {
                        num6 = status;
                    }
                    Win32Exception exception3 = new Win32Exception((int)num6);
                    ADP.TraceExceptionAsReturnValue(exception3);
                    throw exception3;
                }
                }
                if (fileHandle.IsInvalid)
                {
                    Win32Exception exception2 = new Win32Exception(6);
                    ADP.TraceExceptionAsReturnValue(exception2);
                    throw exception2;
                }
                if (System.Data.SqlTypes.UnsafeNativeMethods.GetFileType(fileHandle) != System.Data.SqlTypes.UnsafeNativeMethods.FileType.Disk)
                {
                    fileHandle.Dispose();
                    throw ADP.Argument(Res.GetString("SqlFileStream_PathNotValidDiskResource"));
                }
                if (access == FileAccess.ReadWrite)
                {
                    uint ioControlCode   = System.Data.SqlTypes.UnsafeNativeMethods.CTL_CODE(9, 0x958, 0, 0);
                    uint cbBytesReturned = 0;
                    if (!System.Data.SqlTypes.UnsafeNativeMethods.DeviceIoControl(fileHandle, ioControlCode, IntPtr.Zero, 0, IntPtr.Zero, 0, out cbBytesReturned, IntPtr.Zero))
                    {
                        Win32Exception exception = new Win32Exception(Marshal.GetLastWin32Error());
                        ADP.TraceExceptionAsReturnValue(exception);
                        throw exception;
                    }
                }
                bool flag = false;
                try
                {
                    new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert();
                    flag      = true;
                    this.m_fs = new FileStream(fileHandle, access, 1, (options & FileOptions.Asynchronous) != FileOptions.None);
                }
                finally
                {
                    if (flag)
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }
            }
            catch
            {
                if ((fileHandle != null) && !fileHandle.IsInvalid)
                {
                    fileHandle.Dispose();
                }
                throw;
            }
            finally
            {
                if (eaBuffer != null)
                {
                    eaBuffer.Dispose();
                    eaBuffer = null;
                }
                if (service != null)
                {
                    service.Dispose();
                    service = null;
                }
                if (str != null)
                {
                    str.Dispose();
                    str = null;
                }
            }
        }
Example #58
0
 public static extern SafeFileHandle CreateFile(string fileName, [MarshalAs(UnmanagedType.U4)] FileAccess fileAccess, [MarshalAs(UnmanagedType.U4)] FileShare fileShare, IntPtr securityAttributes, [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition, [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes, IntPtr template);
Example #59
0
            public override Stream OpenFileStream(string path, FileMode fileMode, FileAccess fileAccess, FileShare shareMode, FileOptions options, bool flushesToDisk)
            {
                ReusableMemoryStream stream;

                this.ExpectedOpenFileStreams.TryGetValue(path, out stream).ShouldEqual(true, "Unexpected access of file: " + path);

                if (this.maxOpenFileStreamFailures > 0)
                {
                    if (this.openFileStreamFailureCount < this.maxOpenFileStreamFailures &&
                        string.Equals(path, this.openFileStreamFailurePath, System.StringComparison.OrdinalIgnoreCase))
                    {
                        ++this.openFileStreamFailureCount;

                        if (this.openFileStreamFailureCount % 2 == 0)
                        {
                            throw new IOException();
                        }
                        else
                        {
                            throw new UnauthorizedAccessException();
                        }
                    }
                }
                else if (this.failuresAcrossOpenExistsAndOverwritePath != null)
                {
                    if (this.failuresAcrossOpenExistsAndOverwriteCount == 0 &&
                        string.Equals(path, this.failuresAcrossOpenExistsAndOverwritePath, System.StringComparison.OrdinalIgnoreCase))
                    {
                        ++this.failuresAcrossOpenExistsAndOverwriteCount;
                        throw new IOException();
                    }
                }

                if (fileMode == FileMode.Create)
                {
                    this.ExpectedFiles[path] = new ReusableMemoryStream(string.Empty);
                }

                this.ExpectedFiles.TryGetValue(path, out stream).ShouldEqual(true, "Unexpected access of file: " + path);
                return(stream);
            }
 /// <inheritdoc />
 public IFileStream Open(FileMode mode, FileAccess access, FileShare share)
 {
     return(_instance.Open(mode, access, share).ToInterface());
 }