public override void WriteAllTextToFile(string filePath, string content) { using (FileStream fileStream = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write)) { fileStream.Write(Encoding.Default.GetBytes(content), 0, content.Length); } }
/// <summary> /// 根据文件大小创建文件。 /// 注意:多个用户同时上传相同文件时,可能会同时创建相同文件。 /// </summary> public void make(string filePath, long len) { //文件不存在则创建 if (string.IsNullOrEmpty(filePath)) { return; } if (!LongPathFile.Exists(filePath)) { var pos = filePath.LastIndexOf('\\'); if (-1 == pos) { pos = filePath.LastIndexOf('/'); } var dir = filePath.Substring(0, pos); //自动创建目录 if (!LongPathDirectory.Exists(dir)) { System.Diagnostics.Debug.WriteLine(string.Format("路径不存在:{0}", dir)); PathTool.createDirectory(dir); } else { System.Diagnostics.Debug.WriteLine(string.Format("路径存在:{0}", dir)); } var fs = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write); fs.SetLength(len); fs.Close(); } }
public override void WriteAllBytesToFile(string filePath, byte[] content) { using (FileStream fileStream = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write)) { fileStream.Write(content, 0, content.Length); } }
public override void CreateFile(string filePath) { using (FileStream fileStream = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write)) { // due to the absence of LongPathFile.Create method we had to invent bycycle // this logic creates file stream, writes nothing there then saves and closes it } }
public override string ReadAllText(string filePath) { using (FileStream fileStream = LongPathFile.Open(filePath, FileMode.Open, FileAccess.Read)) { using (StreamReader fileStreamReader = new StreamReader(fileStream, Encoding.Default)) { return(fileStreamReader.ReadToEnd()); } } }
/// <summary> /// 续传文件 /// </summary> /// <param name="fileRange">文件块</param> /// <param name="path">远程文件完整路径。d:\www\web\upload\201204\10\md5.exe</param> public void write(string path, long offset, Stream fileStm) { //文件已存在,写入数据 FileStream fs = LongPathFile.Open(path, FileMode.Open, FileAccess.Write, FileShare.Write); fs.Seek(offset, SeekOrigin.Begin); byte[] ByteArray = new byte[fileStm.Length]; fileStm.Seek(0, SeekOrigin.Begin); fileStm.Read(ByteArray, 0, (int)fileStm.Length); fs.Write(ByteArray, 0, (int)fileStm.Length); fs.Flush(); fs.Close(); }
public static FileStream Open(string path, FileMode mode) { try { path = DMLibTestConstants.SupportUNCPath ? LongPath.GetFullPath(LongPath.ToUncPath(path)) : LongPath.GetFullPath(path); } catch (Exception) { } return(LongPathFile.Open(path, mode, FileAccess.ReadWrite, FileShare.ReadWrite)); }
///<summary> /// Creates a new file from the given path for ReadWrite, /// different depending on whether we're in a transaction or not. ///</summary> ///<param name = "path">Path to create file at.</param> ///<returns>A filestream for the path.</returns> public FileStream Create(string path) { AssertAllowed(path); #if !MONO var mTx = CurrentTransaction(); if (mTx.HasValue) { return(((IFileAdapter)mTx.Value).Create(path)); } #endif return(LongPathFile.Open(path, FileMode.Create, FileAccess.ReadWrite)); }
public virtual Stream Open(FileMode fileMode, FileAccess fileAccess, FileShare fileShare) { if (!Exists && !Parent.Exists) { if (fileMode == FileMode.Create || fileMode == FileMode.CreateNew || fileMode == FileMode.OpenOrCreate) { Parent.Create(); } } Validate.FileAccess(fileMode, fileAccess); return(LongPathFile.Open(filePath, fileMode, fileAccess, fileShare)); }
private void OnCreateFileButtonClick(object sender, EventArgs e) { try { string path = Path.Combine(this.currentPath.Text, fileNameTextBox.Text); using (FileStream fs = LongPathFile.Open(path, FileMode.Create, FileAccess.Read)) { } } catch (ArgumentException ex) { ShowError(ex); } catch (IOException ex) { ShowError(ex); } catch (UnauthorizedAccessException ex) { ShowError(ex); } RefreshFileList(); }
public void GenerateComponent(IProject project, IComponentDescriptor cdesc) { var docproj = project as DocumentationProject; if (docproj == null) { throw new ArgumentException("Expected a documentation project"); } var docs = ((DescriptorBase)cdesc).GetDocumentation(); string prefix = cdesc.GetFullName().Replace(".", "/"); foreach (var doc in docs.Documents) { string legalName = doc.Name.Replace('<', '_').Replace('>', '_'); string name = prefix + "/" + legalName; string path = docproj.AddFile(name); var fs = LongPathFile.Open(path, FileMode.Create, FileAccess.Write); var wr = new StreamWriter(fs); wr.WriteLine(doc.Content.ToString()); wr.Close(); } }
/// <summary> /// Opens a file in the specified mode with read, write, or read/write access and the specified sharing option. /// </summary> /// <param name="mode">A <see cref="FileMode"/> constant specifying the mode (for example, <see cref="FileMode.Open"/> or <see cref="FileMode.Append"/>) in which to open the file.</param> /// <param name="access">A <see cref="FileAccess"/> constant specifying whether to open the file with <see cref="FileAccess.Read"/>, <see cref="FileAccess.Write"/>, or <see cref="FileAccess.ReadWrite"/> file access.</param> /// <param name="share">A <see cref="FileShare"/> constant specifying the type of access other <see cref="FileStream"/> objects have to this file.</param> /// <returns>A <see cref="FileStream"/> object opened with the specified mode, access, and sharing options.</returns> /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception> /// <exception cref="FileNotFoundException">The file is not found.</exception> /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive.</exception> /// <exception cref="IOException">An I/O error occurred while creating the file.</exception> public FileStream Open(FileMode mode, FileAccess access, FileShare share) { return(LongPathFile.Open(this.NormalizedPath, mode, access, share)); }
/// <summary> /// Opens a file in the specified mode. /// </summary> /// <param name="mode">A <see cref="FileMode"/> constant specifying the mode (for example, <see cref="FileMode.Open"/> or <see cref="FileMode.Append"/>) in which to open the file.</param> /// <returns>A file opened in the specified mode, with read/write access and unshared.</returns> /// <exception cref="UnauthorizedAccessException">The caller does not have the required permission.</exception> /// <exception cref="FileNotFoundException">The file is not found.</exception> /// <exception cref="DirectoryNotFoundException">The specified path is invalid (for example, it is on an unmapped drive.</exception> /// <exception cref="IOException">An I/O error occurred while creating the file.</exception> public FileStream Open(FileMode mode) { return(LongPathFile.Open(this.NormalizedPath, mode, FileAccess.ReadWrite, FileShare.None)); }
private async Task OpenInputStreamAsync() { Debug.Assert( State.OpenInputStream == this.state, "OpenInputStreamAsync called, but state is not OpenInputStream."); this.hasWork = false; await Task.Run(() => { this.NotifyStarting(); this.Controller.CheckCancellation(); if (this.transferJob.Source.Type == TransferLocationType.Stream) { StreamLocation streamLocation = this.transferJob.Source as StreamLocation; this.inputStream = streamLocation.Stream; this.ownsStream = false; if (!this.inputStream.CanRead) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportReadException, "inputStream")); } if (!this.inputStream.CanSeek) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportSeekException, "inputStream")); } } else { FileLocation fileLocation = this.transferJob.Source as FileLocation; Debug.Assert( null != fileLocation, "Initializing StreamedReader instance, but source is neither a stream nor a file"); try { if (fileLocation.RelativePath != null && fileLocation.RelativePath.Length > Constants.MaxRelativePathLength) { string errorMessage = string.Format( CultureInfo.CurrentCulture, Resources.RelativePathTooLong, fileLocation.RelativePath); throw new TransferException(TransferErrorCode.OpenFileFailed, errorMessage); } #if DOTNET5_4 string filePath = fileLocation.FilePath; if (Interop.CrossPlatformHelpers.IsWindows) { filePath = LongPath.ToUncPath(fileLocation.FilePath); } // Attempt to open the file first so that we throw an exception before getting into the async work this.inputStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.Read); #else this.inputStream = LongPathFile.Open( fileLocation.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); #endif this.ownsStream = true; } catch (Exception ex) { if ((ex is NotSupportedException) || (ex is IOException) || (ex is UnauthorizedAccessException) || (ex is SecurityException) || (ex is ArgumentException && !(ex is ArgumentNullException))) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToOpenFileException, fileLocation.FilePath, ex.Message); throw new TransferException( TransferErrorCode.OpenFileFailed, exceptionMessage, ex); } else { throw; } } } }); this.SharedTransferData.TotalLength = this.inputStream.Length; int count = (int)Math.Ceiling((double)(this.SharedTransferData.TotalLength - this.transferJob.CheckPoint.EntryTransferOffset) / this.SharedTransferData.BlockSize); if (null != this.transferJob.CheckPoint.TransferWindow) { count += this.transferJob.CheckPoint.TransferWindow.Count; } this.lastTransferWindow = new Queue <long>(this.transferJob.CheckPoint.TransferWindow); this.md5HashStream = new MD5HashStream( this.inputStream, this.transferJob.CheckPoint.EntryTransferOffset, true); this.PreProcessed = true; // This reader will come into 'Finish' state after all chunks are read and MD5 calculation completes. // So initialize the CountDownEvent to count (number of chunks to read) + 1 (md5 calculation). this.countdownEvent = new CountdownEvent(count + 1); if (0 != count) { // Change the state to 'ReadStream' before awaiting MD5 calculation task to not block the reader. this.state = State.ReadStream; this.hasWork = true; } if (!this.md5HashStream.FinishedSeparateMd5Calculator) { await Task.Run(() => { this.md5HashStream.CalculateMd5(this.Scheduler.MemoryManager, this.Controller.CheckCancellation); }); } this.SetChunkFinish(); }
public override Stream Open(FileMode fileMode, FileAccess fileAccess, FileShare fileShare, int bufSize, FileOptions fileOptions) { PrepareOpen(fileMode, fileAccess); return(LongPathFile.Open(Path, fileMode, fileAccess, fileShare)); }
public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share) { return(LongPathFile.Open(path, mode, access, share)); }
private async Task OpenInputStreamAsync() { Debug.Assert( State.OpenInputStream == this.state, "OpenInputStreamAsync called, but state is not OpenInputStream."); if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0) { return; } await Task.Yield(); this.NotifyStarting(); this.Controller.CheckCancellation(); if (this.transferJob.Source.Type == TransferLocationType.Stream) { StreamLocation streamLocation = this.transferJob.Source as StreamLocation; this.inputStream = streamLocation.Stream; this.ownsStream = false; if (!this.inputStream.CanRead) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportReadException, "inputStream")); } } else { FileLocation fileLocation = this.transferJob.Source as FileLocation; Debug.Assert( null != fileLocation, "Initializing StreamedReader instance, but source is neither a stream nor a file"); try { if (fileLocation.RelativePath != null && fileLocation.RelativePath.Length > Constants.MaxRelativePathLength) { string errorMessage = string.Format( CultureInfo.CurrentCulture, Resources.RelativePathTooLong, fileLocation.RelativePath); throw new TransferException(TransferErrorCode.OpenFileFailed, errorMessage); } this.filePath = fileLocation.FilePath.ToLongPath(); #if DOTNET5_4 // Attempt to open the file first so that we throw an exception before getting into the async work this.inputStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.Read); #else this.inputStream = LongPathFile.Open( this.filePath, FileMode.Open, FileAccess.Read, FileShare.Read); #endif this.ownsStream = true; } catch (Exception ex) { if ((ex is NotSupportedException) || (ex is IOException) || (ex is UnauthorizedAccessException) || (ex is SecurityException) || (ex is ArgumentException && !(ex is ArgumentNullException))) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToOpenFileException, fileLocation.FilePath, ex.Message); throw new TransferException( TransferErrorCode.OpenFileFailed, exceptionMessage, ex); } else { throw; } } } try { this.SharedTransferData.TotalLength = this.inputStream.Length; } catch (NotSupportedException) { this.SharedTransferData.TotalLength = -1; } // Only do calculation related to transfer window when the file contains multiple chunks. if (!this.EnableOneChunkFileOptimization) { var checkpoint = this.transferJob.CheckPoint; checkpoint.TransferWindow.Sort(); this.readLength = checkpoint.EntryTransferOffset; if (checkpoint.TransferWindow.Any()) { // The size of last block can be smaller than BlockSize. this.readLength -= Math.Min(checkpoint.EntryTransferOffset - checkpoint.TransferWindow.Last(), this.SharedTransferData.BlockSize); this.readLength -= (checkpoint.TransferWindow.Count - 1) * this.SharedTransferData.BlockSize; } if (this.readLength < 0) { throw new InvalidOperationException(Resources.RestartableInfoCorruptedException); } else if ((checkpoint.EntryTransferOffset > 0) && (!this.inputStream.CanSeek)) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportSeekException, "inputStream")); } this.lastTransferWindow = new Queue <long>(this.transferJob.CheckPoint.TransferWindow); } this.md5HashStream = new MD5HashStream( this.inputStream, this.transferJob.CheckPoint.EntryTransferOffset, true); this.PreProcessed = true; if (this.readLength != this.SharedTransferData.TotalLength) { // Change the state to 'ReadStream' before awaiting MD5 calculation task to not block the reader. this.state = State.ReadStream; this.workToken = 1; } else { Interlocked.Exchange(ref this.readCompleted, 1); } if (!this.md5HashStream.FinishedSeparateMd5Calculator) { await Task.Run(() => { this.md5HashStream.CalculateMd5(this.Scheduler.MemoryManager, this.Controller.CheckCancellation); }); } this.SetChunkFinish(); }
public static FileStream Open(string path, FileMode mode) { return(LongPathFile.Open(path, mode, FileAccess.ReadWrite, FileShare.ReadWrite)); }
private async Task OpenInputStreamAsync() { Debug.Assert( State.OpenInputStream == this.state, "OpenInputStreamAsync called, but state is not OpenInputStream."); if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0) { return; } await Task.Yield(); this.NotifyStarting(); this.Controller.CheckCancellation(); if (this.transferJob.Source.Type == TransferLocationType.Stream) { StreamLocation streamLocation = this.transferJob.Source as StreamLocation; this.inputStream = streamLocation.Stream; this.ownsStream = false; if (!this.inputStream.CanRead) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportReadException, "inputStream")); } } else { FileLocation fileLocation = this.transferJob.Source as FileLocation; Debug.Assert( null != fileLocation, "Initializing StreamedReader instance, but source is neither a stream nor a file"); try { if (fileLocation.RelativePath != null && fileLocation.RelativePath.Length > Constants.MaxRelativePathLength) { string errorMessage = string.Format( CultureInfo.CurrentCulture, Resources.RelativePathTooLong, fileLocation.RelativePath); throw new TransferException(TransferErrorCode.OpenFileFailed, errorMessage); } #if DOTNET5_4 string filePath = fileLocation.FilePath; if (Interop.CrossPlatformHelpers.IsWindows) { filePath = LongPath.ToUncPath(fileLocation.FilePath); } // Attempt to open the file first so that we throw an exception before getting into the async work this.inputStream = new FileStream( filePath, FileMode.Open, FileAccess.Read, FileShare.Read); #else this.inputStream = LongPathFile.Open( fileLocation.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); #endif this.ownsStream = true; } catch (Exception ex) { if ((ex is NotSupportedException) || (ex is IOException) || (ex is UnauthorizedAccessException) || (ex is SecurityException) || (ex is ArgumentException && !(ex is ArgumentNullException))) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToOpenFileException, fileLocation.FilePath, ex.Message); throw new TransferException( TransferErrorCode.OpenFileFailed, exceptionMessage, ex); } else { throw; } } } }).ConfigureAwait(false);
private async Task HandleOutputStreamAsync() { this.hasWork = false; await Task.Run(async() => { // Only do calculation related to transfer window when the file contains multiple chunks. if (!this.EnableOneChunkFileOptimization) { // We do check point consistancy validation in reader, and directly use it in writer. if ((null != this.TransferJob.CheckPoint.TransferWindow) && this.TransferJob.CheckPoint.TransferWindow.Any()) { this.TransferJob.CheckPoint.TransferWindow.Sort(); this.expectOffset = this.TransferJob.CheckPoint.TransferWindow[0]; } else { this.expectOffset = this.TransferJob.CheckPoint.EntryTransferOffset; } } if (TransferLocationType.Stream == this.TransferJob.Destination.Type) { Stream streamInDestination = (this.TransferJob.Destination as StreamLocation).Stream; if (!streamInDestination.CanWrite) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportWriteException, "outputStream")); } if (!streamInDestination.CanSeek) { throw new NotSupportedException(string.Format( CultureInfo.CurrentCulture, Resources.StreamMustSupportSeekException, "outputStream")); } this.outputStream = streamInDestination; } else { string filePath = (this.TransferJob.Destination as FileLocation).FilePath; if (!this.Controller.IsForceOverwrite) { await this.Controller.CheckOverwriteAsync( LongPathFile.Exists(filePath), this.TransferJob.Source.Instance, filePath); } this.Controller.CheckCancellation(); try { FileMode fileMode = 0 == this.expectOffset ? FileMode.OpenOrCreate : FileMode.Open; #if DOTNET5_4 string longFilePath = filePath; if (Interop.CrossPlatformHelpers.IsWindows) { longFilePath = LongPath.ToUncPath(longFilePath); } // Attempt to open the file first so that we throw an exception before getting into the async work this.outputStream = new FileStream( longFilePath, fileMode, FileAccess.ReadWrite, FileShare.None); #else this.outputStream = LongPathFile.Open( filePath, fileMode, FileAccess.ReadWrite, FileShare.None); #endif this.ownsStream = true; } catch (Exception ex) { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToOpenFileException, filePath, ex.Message); throw new TransferException( TransferErrorCode.OpenFileFailed, exceptionMessage, ex); } } this.outputStream.SetLength(this.SharedTransferData.TotalLength); this.md5HashStream = new MD5HashStream( this.outputStream, this.expectOffset, !this.SharedTransferData.DisableContentMD5Validation); if (this.md5HashStream.FinishedSeparateMd5Calculator) { this.state = State.Write; } else { this.state = State.CalculateMD5; } this.PreProcessed = true; // Switch state internal for one chunk small file. if (this.EnableOneChunkFileOptimization && State.Write == this.state && ((this.SharedTransferData.TotalLength == this.expectOffset) || this.SharedTransferData.AvailableData.ContainsKey(this.expectOffset))) { this.isStateSwitchedInternal = true; await this.WriteChunkDataAsync().ConfigureAwait(false); } else { this.hasWork = true; } }); }
public override FileStream OpenFile(string filePath) { return(LongPathFile.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite)); }