Esempio n. 1
0
 public LogStore(
     string path,
     FileMode mode,
     FileAccess access)
     : this(path, mode, access, FileShare.None)
 {
 }
		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
		}
Esempio n. 3
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);
        }
Esempio n. 4
0
 public void Compress(string sourceFilename, string targetFilename, FileMode fileMode, OutArchiveFormat archiveFormat,
     CompressionMethod compressionMethod, CompressionLevel compressionLevel, ZipEncryptionMethod zipEncryptionMethod,
     string password, int bufferSize, int preallocationPercent, bool check, Dictionary<string, string> customParameters)
 {
     bufferSize *= this._sectorSize;
     SevenZipCompressor compressor = new SevenZipCompressor();
     compressor.FastCompression = true;
     compressor.ArchiveFormat = archiveFormat;
     compressor.CompressionMethod = compressionMethod;
     compressor.CompressionLevel = compressionLevel;
     compressor.DefaultItemName = Path.GetFileName(sourceFilename);
     compressor.DirectoryStructure = false;
     compressor.ZipEncryptionMethod = zipEncryptionMethod;
     foreach (var pair in customParameters)
     {
         compressor.CustomParameters[pair.Key] = pair.Value;
     }
     using (FileStream sourceFileStream = new FileStream(sourceFilename,
         FileMode.Open, FileAccess.Read, FileShare.None, bufferSize,
         Win32.FileFlagNoBuffering | FileOptions.SequentialScan))
     {
         using (FileStream targetFileStream = new FileStream(targetFilename,
                fileMode, FileAccess.ReadWrite, FileShare.ReadWrite, 8,
                FileOptions.WriteThrough | Win32.FileFlagNoBuffering))
         {
             this.Compress(compressor, sourceFileStream, targetFileStream,
                 password, preallocationPercent, check, bufferSize);
         }
     }
 }
	/**
     * open file.
     * @param void.
     * @return void.
     */
	public bool Open(string strFileName, FileMode eMode, FileAccess eAccess)
	{
		if (string.IsNullOrEmpty(strFileName))
		{
			return false;
		}
		
		if ((FileMode.Open == eMode) && !File.Exists(strFileName))
		{
			return false;
		}
		
		try
		{
			m_cStream = new FileStream(strFileName, eMode, eAccess);
		}
		catch (Exception cEx)
		{
			Console.Write(cEx.Message);
		}
		
		if (null == m_cStream)
		{
			return false;
		}
		
		m_bOpen = true;
		return true;
	}
Esempio n. 6
0
        // This plug basically forwards all calls to the $$InnerStream$$ stream, which is supplied by the file system.

        //  public static unsafe void Ctor(String aThis, [FieldAccess(Name = "$$Storage$$")]ref Char[] aStorage, Char[] aChars, int aStartIndex, int aLength,

        public static void Ctor(FileStream aThis, string aPathname, FileMode aMode,
            [FieldAccess(Name = "$$InnerStream$$")] ref Stream innerStream)
        {
            Global.mFileSystemDebugger.SendInternal("FileStream.Ctor:");

            innerStream = InitializeStream(aPathname, aMode);
        }
 private static void FileModeChanged(string[] assets, FileMode mode)
 {
     if (Provider.enabled && Provider.PromptAndCheckoutIfNeeded(assets, ""))
     {
         Provider.SetFileMode(assets, mode);
     }
 }
 private static FileStream GetFileStream(string fileName, FileMode mode)
 {
     using (var storageFile = IsolatedStorageFile.GetUserStoreForApplication())
     {
         return new IsolatedStorageFileStream(fileName, mode, storageFile);
     }
 }
        /// <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));
        }
Esempio n. 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);
        }
Esempio n. 11
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
		}
		public void Process(FileMode mode, bool agreement)
		{
			PropertyBag["mode"] = mode;
			PropertyBag["agreement"] = agreement;
			
			RenderView("result");
		}
Esempio n. 13
0
 private static extern SafeFileHandle CreateFile(string filename,
                                FileAccess desiredAccess,
                                FileShare shareMode,
                                IntPtr attributes,
                                FileMode creationDisposition,
                                uint flagsAndAttributes = 0,
                                IntPtr templateFile = default(IntPtr));
    public static void WriteTextToFile(string strFilePath, string strText, FileMode fileMode)
    {
        StreamWriter SW = File.AppendText(strFilePath);
        FileStream FS;
        char[] arrChar = strText.ToCharArray();

        try
        {
            if(FileExists(strFilePath))
            {
                SW.WriteLine(strText);
            }
            else
            {
                FS = File.Open(strFilePath, fileMode);

                for(int i = 0; i < strText.Length; i++)
                {
                    FS.WriteByte(Convert.ToByte(arrChar[i]));
                }
                FS.Flush();
                FS.Close();
            }
        }
        catch
        {
        }
        finally
        {
            SW.Flush();
            SW.Close();
        }
    }
		public RemoteFileSystemFileStream(RemoteFileSystem RemoteFileSystem, String FileName, FileMode FileMode)
			: base(RemoteFileSystem, (Lazy<Stream>)null)
		{
			this.RemoteFileSystem = RemoteFileSystem;
			this.FileName = FileName;
			this.FileMode = FileMode;
		}
Esempio n. 16
0
        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;
            }
        }
Esempio n. 17
0
        protected ShapefileWriter(string path, ShapefileHeader header, FileMode fileMode, FileAccess fileAccess)
        {
            _writerShape = new BinaryWriter(new FileStream(path, fileMode, fileAccess));
            _writerIndex = new BinaryWriter(new FileStream(Path.ChangeExtension(path, ".shx"), fileMode, fileAccess));

            _header = header;
        }
Esempio n. 18
0
		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());
		}
 public MongoGridFSStream(
     MongoGridFSFileInfo fileInfo,
     FileMode mode
 )
     : this(fileInfo, mode, FileAccess.ReadWrite)
 {
 }
Esempio n. 20
0
        /// <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);
        }
 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);
 }
        private void WriteFile(string filename, byte[] content, FileMode fileMode)
        {
            Stream target = null;
            BinaryWriter writer = null;

            try
            {
                target = File.Open(filename, fileMode);
                writer = new BinaryWriter(target);

                writer.Write(content);
            }
            catch (Exception ex)
            {
                throw new Exception("Could not write to file: " + filename + " - " + ex.Message);
            }
            finally
            {
                if (target != null)
                {
                    target.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Esempio n. 23
0
		internal static void FileAccess(FileMode fileMode, FileAccess fileAccess)
		{
			// exception if:

			// !write && append
			// !write && create
			// !write && createNew
			// !write && truncate

			var noWrite = (fileAccess & System.IO.FileAccess.Write) == 0;
			if (noWrite && fileMode == FileMode.CreateNew)
				throw new ArgumentException(string.Format(
					"Can only open files in {0} mode when requesting FileAccess.Write access.", fileMode));

			if (noWrite && fileMode == FileMode.Truncate)
				throw new IOException("Cannot truncate a file if file mode doesn't include WRITE.");

			// or if:
			// readwrite && append
			// read && append

			if (fileAccess == System.IO.FileAccess.Read && fileMode == FileMode.Append)
				throw new ArgumentException("Cannot open file in read-mode when having FileMode.Append");

			//if (
			//    ((fileMode == FileMode.Append) && fileAccess != FileAccess.Write) ||
			//    ((fileMode == FileMode.CreateNew || fileMode == FileMode.Create || fileMode == FileMode.Truncate)
			//     && (fileAccess != FileAccess.Write && fileAccess != FileAccess.ReadWrite)) ||
			//    false //((Exists && fileMode == FileMode.OpenOrCreate && fileAccess == FileAccess.Write))
			//    )
		}
 public static void SerializeToFile(object obj, string file, FileMode fileMode, XmlSerializerNamespaces namespaces, bool omitXmlDeclaration)
 {
     using (FileStream fileStream = new FileStream(file, fileMode))
     {
         SerializeToStream(obj, fileStream, namespaces, omitXmlDeclaration);
     }
 }
Esempio n. 25
0
 // uint GetMode( FileMode mode )
 // Converts the filemode constant to win32 constant
 #region GetMode
 private static uint GetMode(FileMode mode)
 {
     uint umode = 0;
     switch (mode)
     {
         case FileMode.CreateNew:
             umode = CREATE_NEW;
             break;
         case FileMode.Create:
             umode = CREATE_ALWAYS;
             break;
         case FileMode.Append:
             umode = OPEN_ALWAYS;
             break;
         case FileMode.Open:
             umode = OPEN_EXISTING;
             break;
         case FileMode.OpenOrCreate:
             umode = OPEN_ALWAYS;
             break;
         case FileMode.Truncate:
             umode = TRUNCATE_EXISTING;
             break;
     }
     return umode;
 }
Esempio n. 26
0
 private static extern IntPtr CreateFile(string fileName, 
     FILE_ACCESS_RIGHTS access,
     FileShare share,
     int securityAttributes,
     FileMode creation,
     FILE_FLAGS flags,
     IntPtr templateFile);
Esempio n. 27
0
 public Output(string filename, FileMode mode)
 {
     StandardOutput = IsStandardOutput(filename);
     Name = StandardOutput ? "(standard output)" : filename;
     Mode = mode;
     Open = () => StandardOutput ? Console.OpenStandardOutput() : File.Open(Name, Mode);
 }
Esempio n. 28
0
        public static IStream FromFile(string fileName, FileMode mode, StreamInfo streamInfo)
        {
            if (fileName == null)
                throw new ArgumentNullException("fileName");

            return FromStream(File.Open(fileName, mode), streamInfo ?? StreamInfo.FromFile(fileName));
        }
 public static extern SafeFileHandle CreateFile(String fileName,
     FileAccess desiredAccess,
     FileShare shareMode,
     IntPtr securityAttrs,
     FileMode creationDisposition,
     int flagsAndAttributes,
     IntPtr templateFile);
Esempio n. 30
0
 public override void Open(FileMode mode = FileMode.OpenOrCreate)
 {
     if (this.isOpen)
     {
         Console.WriteLine("DataFile::Open File is already open: " + this.name);
         return;
     }
     if (!this.OpenFileStream(this.name, mode))
     {
         this.beginPosition = 62L;
         this.endPosition = 62L;
         this.keysPosition = 62L;
         this.freePosition = 62L;
         this.keysLength = 0;
         this.freeLength = 0;
         this.keysNumber = 0;
         this.freeNumber = 0;
         this.isModified = true;
         base.WriteHeader();
     }
     else
     {
         if (!base.ReadHeader())
         {
             Console.WriteLine("DataFile::Open Error opening file " + this.name);
             return;
         }
         base.ReadKeys();
         base.ReadFree();
     }
     this.isOpen = true;
 }
Esempio n. 31
0
 internal AsyncWindowsFileStreamStrategy(string path, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize)
     : base(path, mode, access, share, options, preallocationSize)
 {
 }
Esempio n. 32
0
 private static byte[] CreateSendFileRequest(String command, String path, FileMode mode)
 {
     return(CreateSendFileRequest(Encoding.Default.GetBytes(command), Encoding.Default.GetBytes(path), mode));
 }
Esempio n. 33
0
 public Stream CreateFileStream(string filename, FileMode mode, FileAccess access, FileShare share)
 {
     return(new FileStream(filename, mode, access, share));
 }
Esempio n. 34
0
 public Stream CreateFileStream(string filename, FileMode mode)
 {
     return(new FileStream(filename, mode));
 }
Esempio n. 35
0
 public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share)
 {
     return(new FileStream(path, mode, access, share, NativeFileStream.BufferSizeDefault));
 }
Esempio n. 36
0
 public static FileStream Open(String path, FileMode mode)
 {
     return(new FileStream(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None, NativeFileStream.BufferSizeDefault));
 }
Esempio n. 37
0
 private static FileStreamStrategy ChooseStrategyCore(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, long preallocationSize)
 => new Net5CompatFileStreamStrategy(path, mode, access, share, bufferSize == 0 ? 1 : bufferSize, options, preallocationSize);
Esempio n. 38
0
 public static FileStream Open(string path, FileMode mode, FileAccess access)
 {
     return(Open(path, mode, access, FileShare.None));
 }
Esempio n. 39
0
        public static TaskFunc ProcessNand(string nandDump, NandTasks task)
        {
            return((Tasker tasker, Object sync) =>
            {
                NandTasks[] validTasks = { NandTasks.DumpNand, NandTasks.DumpNandB, NandTasks.DumpNandC, NandTasks.FlashNandB, NandTasks.FlashNandC, NandTasks.FormatNandC };
                if (!validTasks.Contains(task))
                {
                    throw new ArgumentOutOfRangeException("task");
                }

                if (task == NandTasks.FlashNandB && !Files.CheckFileType.IsSquashFs(nandDump))
                {
                    throw new Exception(Properties.Resources.InvalidHsqs);
                }


                bool isTar = false;
                if (task == NandTasks.FlashNandC)
                {
                    isTar = Files.CheckFileType.IsTar(nandDump);
                    if (!(isTar || Files.CheckFileType.IsExtFs(nandDump)))
                    {
                        throw new Exception(Properties.Resources.InvalidUserDataBackup);
                    }
                }

                long partitionSize = 300 * 1024 * 1024;
                var splitStream = new SplitterStream(Program.debugStreams);
                switch (task)
                {
                case NandTasks.DumpNandB:
                case NandTasks.FlashNandB:
                    hakchi.Shell.Execute("umount /newroot");
                    hakchi.Shell.Execute("cryptsetup close root-crypt");
                    hakchi.Shell.ExecuteSimple("cryptsetup open /dev/nandb root-crypt --type plain --cipher aes-xts-plain --key-file /key-file", 2000, true);

                    if (task == NandTasks.DumpNandB)
                    {
                        partitionSize = long.Parse(hakchi.Shell.ExecuteSimple("echo $((($(hexdump -e '1/4 \"%u\"' -s $((0x28)) -n 4 /dev/mapper/root-crypt)+0xfff)/0x1000))", throwOnNonZero: true).Trim()) * 4 * 1024;
                    }

                    if (task == NandTasks.FlashNandB)
                    {
                        partitionSize = long.Parse(hakchi.Shell.ExecuteSimple("blockdev --getsize64 /dev/mapper/root-crypt", throwOnNonZero: true));
                    }

                    break;

                case NandTasks.DumpNandC:
                    hakchi.Shell.Execute("hakchi mount_base", null, null, null, 0, true);
                    partitionSize = long.Parse(hakchi.Shell.ExecuteSimple("df -B 1 | grep /newroot/var/lib | head -n 1 | awk -e '{print $3 }'", throwOnNonZero: true).Trim());
                    break;

                case NandTasks.FlashNandC:
                    partitionSize = long.Parse(hakchi.Shell.ExecuteSimple("blockdev --getsize64 /dev/nandc", throwOnNonZero: true));
                    break;

                case NandTasks.DumpNand:
                    partitionSize = 536870912;
                    break;

                case NandTasks.FormatNandC:
                    hakchi.Shell.Execute("cat > /bin/mke2fs; chmod +x /bin/mke2fs", File.OpenRead(Shared.PathCombine(Program.BaseDirectoryInternal, "tools", "arm", "mke2fs.static")), null, null, 0, true);
                    hakchi.Shell.Execute("hakchi umount_base", null, splitStream, splitStream);
                    hakchi.Shell.Execute("yes | mke2fs -t ext4 -L data -b 4K -E stripe-width=32 -O ^huge_file,^metadata_csum /dev/nandc", null, splitStream, splitStream, 0, true);
                    hakchi.Shell.Execute("rm /bin/mke2fs");
                    return Conclusion.Success;
                }

                FileMode mode = FileMode.Create;

                if (task == NandTasks.FlashNandC || task == NandTasks.FlashNandB)
                {
                    mode = FileMode.Open;
                }

                tasker.SetStatus(mode == FileMode.Open ? Resources.FlashingNand : Resources.DumpingNand);
                using (var file = new TrackableFileStream(nandDump, mode))
                {
                    if (mode == FileMode.Open && file.Length > partitionSize)
                    {
                        throw new Exception(Resources.ImageTooLarge);
                    }

                    if (mode == FileMode.Create && task != NandTasks.DumpNandC)
                    {
                        file.SetLength(partitionSize);
                    }

                    if (task == NandTasks.DumpNandC)
                    {
                        file.OnProgress += (long position, long length) =>
                        {
                            tasker.OnProgress(Math.Min(position, partitionSize), partitionSize);
                        };
                    }
                    else
                    {
                        file.OnProgress += tasker.OnProgress;
                    }

                    switch (task)
                    {
                    case NandTasks.DumpNandB:
                        Shared.ShellPipe($"dd if=/dev/mapper/root-crypt bs=128K count={(partitionSize / 1024) / 4 }", null, file, throwOnNonZero: true);
                        break;

                    case NandTasks.FlashNandB:
                        Shared.ShellPipe("dd of=/dev/mapper/root-crypt bs=128K", file, throwOnNonZero: true);
                        hakchi.Shell.Execute("cryptsetup close root-crypt", throwOnNonZero: true);
                        break;

                    case NandTasks.DumpNandC:
                        Shared.ShellPipe($"tar -cvC /newroot/var/lib/ .", null, file, null, throwOnNonZero: true);
                        break;

                    case NandTasks.FlashNandC:
                        if (isTar)
                        {
                            hakchi.Shell.Execute("hakchi mount_base", null, null, null, 0, true);
                            hakchi.Shell.Execute("rm -rf /newroot/var/lib/*", null, null, null, 0, true);
                            hakchi.Shell.Execute("tar -xvC /newroot/var/lib/", file, throwOnNonZero: true);
                        }
                        else
                        {
                            Shared.ShellPipe("dd of=/dev/nandc bs=128K", file, throwOnNonZero: true);
                        }
                        break;

                    case NandTasks.DumpNand:
                        Shared.ShellPipe("sntool sunxi_flash phy_read 0 1000", null, file, throwOnNonZero: true);
                        break;
                    }
                    file.Close();
                }

                tasker.SetStatus(Resources.Done);
                tasker.SetProgress(1, 1);
                return Conclusion.Success;
            });
        }
Esempio n. 40
0
 public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(new FileStream(path, mode, access, share));
 }
Esempio n. 41
0
 // ** ctor
 public RawHtmlStream(string path, FileMode mode) : base(path, mode)
 {
 }
Esempio n. 42
0
 public static FileStream Open(string path, FileMode mode)
 {
     return(Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None));
 }
 public virtual Stream CreateFileStream(string filePath, FileMode mode)
 {
     return(new FileStream(filePath, mode));
 }
Esempio n. 44
0
 /// <summary>
 /// Opens a GridFS file with the specified mode.
 /// </summary>
 /// <param name="mode">The mode.</param>
 /// <returns>A stream.</returns>
 public MongoGridFSStream Open(
     FileMode mode
     )
 {
     return(Open(mode, FileAccess.ReadWrite));
 }
Esempio n. 45
0
 /// <inheritdoc />
 public IFileStream Open(string path, FileMode mode)
 {
     return(File.Open(path, mode).ToInterface());
 }
Esempio n. 46
0
 public FileStream(string path, FileMode mode, FileAccess access)
 {
     OpenFile(path, access);
 }
Esempio n. 47
0
 public override Stream Open(string path, FileMode mode)
 {
     return(AfsFile.Open(path, mode));
 }
Esempio n. 48
0
 /// <inheritdoc />
 public IFileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(File.Open(path, mode, access, share).ToInterface());
 }
Esempio n. 49
0
 public abstract Stream GetStream(string path, FileAccess access = FileAccess.Read, FileMode mode = FileMode.OpenOrCreate);
Esempio n. 50
0
 public override Stream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(AfsFile.Open(path, mode, access, share));
 }
 public Stream OpenFileExclusively(string filePath, FileMode fileMode, FileAccess fileAccess)
 {
     return(File.Open(filePath, fileMode, fileAccess, FileShare.None));
 }
Esempio n. 52
0
 public static Stream OpenPathUncached(string path, FileMode mode, System.IO.FileAccess access, FileShare share)
 => OpenPath(path, mode, access, share, FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_WRITE_THROUGH);
Esempio n. 53
0
        /// <summary>
        /// <span style="font-weight:bold;color:#a00;">(Extension Method)</span><br />
        /// Opens an alternate data stream.
        /// </summary>
        /// <param name="file">
        /// The <see cref="FileInfo"/> which contains the stream.
        /// </param>
        /// <param name="streamName">
        /// The name of the stream to open.
        /// </param>
        /// <param name="mode">
        /// One of the <see cref="FileMode"/> values, indicating how the stream is to be opened.
        /// </param>
        /// <returns>
        /// An <see cref="AlternateDataStreamInfo"/> representing the stream.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="file"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="FileNotFoundException">
        /// The specified <paramref name="file"/> was not found.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="streamName"/> contains invalid characters.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// <paramref name="mode"/> is either <see cref="FileMode.Truncate"/> or <see cref="FileMode.Append"/>.
        /// </exception>
        /// <exception cref="IOException">
        /// <para><paramref name="mode"/> is <see cref="FileMode.Open"/>, and the stream doesn't exist.</para>
        /// <para>-or-</para>
        /// <para><paramref name="mode"/> is <see cref="FileMode.CreateNew"/>, and the stream already exists.</para>
        /// </exception>
        /// <exception cref="SecurityException">
        /// The caller does not have the required permission.
        /// </exception>
        /// <exception cref="UnauthorizedAccessException">
        /// The caller does not have the required permission, or the file is read-only.
        /// </exception>
        public static AlternateDataStreamInfo GetAlternateDataStream(this FileSystemInfo file, string streamName, FileMode mode)
        {
            if (null == file)
            {
                throw new ArgumentNullException("file");
            }
            if (!file.Exists)
            {
                throw new FileNotFoundException(null, file.FullName);
            }
            SafeNativeMethods.ValidateStreamName(streamName);

            if (FileMode.Truncate == mode || FileMode.Append == mode)
            {
                throw new NotSupportedException(string.Format(Resources.Culture,
                                                              Resources.Error_InvalidMode, mode));
            }

            FileIOPermissionAccess permAccess = (FileMode.Open == mode) ? FileIOPermissionAccess.Read : FileIOPermissionAccess.Read | FileIOPermissionAccess.Write;

            new FileIOPermission(permAccess, file.FullName).Demand();

            string path   = SafeNativeMethods.BuildStreamPath(file.FullName, streamName);
            bool   exists = -1 != SafeNativeMethods.SafeGetFileAttributes(path);

            if (!exists && FileMode.Open == mode)
            {
                throw new IOException(string.Format(Resources.Culture,
                                                    Resources.Error_StreamNotFound, streamName, file.Name));
            }
            if (exists && FileMode.CreateNew == mode)
            {
                throw new IOException(string.Format(Resources.Culture,
                                                    Resources.Error_StreamExists, streamName, file.Name));
            }

            return(new AlternateDataStreamInfo(file.FullName, streamName, path, exists));
        }
Esempio n. 54
0
 /// <summary>
 /// Not used
 /// </summary>
 /// <param name="content">Not used</param>
 /// <param name="mode">Not used</param>
 /// <returns>The result of the write or original content</returns>
 public override byte[] Write(byte[] content, FileMode mode = FileMode.Create) => Write(content.ToString(Encoding.UTF8), mode).ToByteArray();
Esempio n. 55
0
 public override FileStreamBase Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent)
 {
     return(new UnixFileStream(fullPath, mode, access, share, bufferSize, options, parent));
 }
Esempio n. 56
0
 /// <summary>
 /// Opens an alternate data stream.
 /// </summary>
 /// <param name="filePath">
 /// The path of the file which contains the stream.
 /// </param>
 /// <param name="streamName">
 /// The name of the stream to open.
 /// </param>
 /// <param name="mode">
 /// One of the <see cref="FileMode"/> values, indicating how the stream is to be opened.
 /// </param>
 /// <returns>
 /// An <see cref="AlternateDataStreamInfo"/> representing the stream.
 /// </returns>
 /// <exception cref="ArgumentNullException">
 /// <paramref name="filePath"/> is <see langword="null"/> or an empty string.
 /// </exception>
 /// <exception cref="FileNotFoundException">
 /// The specified <paramref name="filePath"/> was not found.
 /// </exception>
 /// <exception cref="ArgumentException">
 /// <para><paramref name="filePath"/> is not a valid file path.</para>
 /// <para>-or-</para>
 /// <para><paramref name="streamName"/> contains invalid characters.</para>
 /// </exception>
 /// <exception cref="NotSupportedException">
 /// <paramref name="mode"/> is either <see cref="FileMode.Truncate"/> or <see cref="FileMode.Append"/>.
 /// </exception>
 /// <exception cref="IOException">
 /// <para><paramref name="mode"/> is <see cref="FileMode.Open"/>, and the stream doesn't exist.</para>
 /// <para>-or-</para>
 /// <para><paramref name="mode"/> is <see cref="FileMode.CreateNew"/>, and the stream already exists.</para>
 /// </exception>
 /// <exception cref="SecurityException">
 /// The caller does not have the required permission.
 /// </exception>
 /// <exception cref="UnauthorizedAccessException">
 /// The caller does not have the required permission, or the file is read-only.
 /// </exception>
 public static AlternateDataStreamInfo GetAlternateDataStream(string filePath, string streamName, FileMode mode)
 {
     if (string.IsNullOrEmpty(filePath))
     {
         throw new ArgumentNullException("filePath");
     }
     return(CreateInfo(filePath).GetAlternateDataStream(streamName, mode));
 }
Esempio n. 57
0
        public static OpenFlags ToOpenFlags(FileMode mode, FileAccess access)
        {
            OpenFlags flags = 0;

            switch (mode)
            {
            case FileMode.CreateNew:
                flags = OpenFlags.O_CREAT | OpenFlags.O_EXCL;
                break;

            case FileMode.Create:
                flags = OpenFlags.O_CREAT | OpenFlags.O_TRUNC;
                break;

            case FileMode.Open:
                // do nothing
                break;

            case FileMode.OpenOrCreate:
                flags = OpenFlags.O_CREAT;
                break;

            case FileMode.Truncate:
                flags = OpenFlags.O_TRUNC;
                break;

            case FileMode.Append:
                flags = OpenFlags.O_APPEND;
                break;

            default:
                throw new ArgumentException(Locale.GetText("Unsupported mode value"), "mode");
            }

            // Is O_LARGEFILE supported?
            int _v;

            if (TryFromOpenFlags(OpenFlags.O_LARGEFILE, out _v))
            {
                flags |= OpenFlags.O_LARGEFILE;
            }

            switch (access)
            {
            case FileAccess.Read:
                flags |= OpenFlags.O_RDONLY;
                break;

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

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

            default:
                throw new ArgumentOutOfRangeException(Locale.GetText("Unsupported access value"), "access");
            }

            return(flags);
        }
Esempio n. 58
0
        /// <summary>
        /// Method to create the encryption cipher.
        /// </summary>
        /// <returns>The encryption cypher.</returns>
        private RijndaelManaged CreateCipher()
        {
            RijndaelManaged     aes = new RijndaelManaged();
            IsolatedStorageFile isf = null;

            try
            {
                isf = IsolatedStorageFile.GetUserStoreForAssembly();
            }
            catch (SecurityException)
            {
                isf = IsolatedStorageFile.GetMachineStoreForAssembly();
            }

            FileMode   fm = FileMode.Open;
            FileAccess fa = FileAccess.Read;

            if (!isf.FileExists(Constants.CipherFile))
            {
                fm = FileMode.CreateNew;
                fa = FileAccess.ReadWrite;
            }

            using (IsolatedStorageFileStream ifs = new IsolatedStorageFileStream(Constants.CipherFile, fm, fa, isf))
            {
                string cipherData = string.Empty;
                if (fm == FileMode.Open)
                {
                    using (StreamReader sr = new StreamReader(ifs))
                    {
                        cipherData = sr.ReadLine();
                        string[] cipherInit = cipherData.Split(new char[] { Constants.Pipe });
                        if (cipherInit.Length == 2)
                        {
                            aes.IV  = this.rsa.Decrypt(Convert.FromBase64String(cipherInit[0]), true);
                            aes.Key = this.rsa.Decrypt(Convert.FromBase64String(cipherInit[1]), true);
                        }
                        else
                        {
                            throw new ArgumentException(Resources.ErrorInvalidCipherData);
                        }

                        sr.Close();
                    }
                }
                else
                {
                    cipherData = Convert.ToBase64String(this.rsa.Encrypt(aes.IV, true))
                                 + Constants.Pipe + Convert.ToBase64String(this.rsa.Encrypt(aes.Key, true));

                    using (StreamWriter sw = new StreamWriter(ifs))
                    {
                        sw.WriteLine(cipherData);
                        sw.Flush();
                        sw.Close();
                    }
                }
            }

            return(aes);
        }
Esempio n. 59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:SystemWrapper.IO.FileStreamWrap"/> class with the specified path and creation mode.
 /// </summary>
 /// <param name="path">A relative or absolute path for the file that the current FileStream object will encapsulate.</param>
 /// <param name="mode">A FileMode constant that determines how to open or create the file.</param>
 public void Initialize(string path, FileMode mode)
 {
     FileStreamInstance = new FileStream(path, mode);
 }
Esempio n. 60
0
 public EndianIO(string FileLocation, EndianTypes EndianType, FileMode Mode = FileMode.Open, FileAccess Access = FileAccess.ReadWrite, FileShare Share = FileShare.Read) : this(new FileStream(FileLocation, Mode, Access, Share), EndianType)
 {
     this.FileLocation = FileLocation;
 }