C# FileStream.Flush的代码示例

通过代码示例来学习C# FileStream.Flush方法

通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。


FileStream.Flush是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的FileStream.Flush() 已经帮大家高亮显示了,大家可以重点学习FileStream.Flush() 方法的写法,从而快速掌握该方法的应用。

FileStream.Flush的代码示例1 - WriteToFileOrStream()

    using System.IO;

    #endregion

    #region Private Method


























































    private void WriteToFileOrStream()
    {
      if( _filename != null && !_isCopyingDocument)
      {
        using( var fs = new FileStream( _filename, FileMode.Create ) )
        {
          if( _memoryStream.CanSeek )
          {
            // Write to the beginning of the stream
            _memoryStream.Position = 0;
            HelperFunctions.CopyStream( _memoryStream, fs );
          }
          else
            fs.Write( _memoryStream.ToArray(), 0, (int)_memoryStream.Length );
        }
      }
      else if( _stream.CanSeek )  //Check if stream can be seeked to support System.Web.HttpResponseStream.
      {
        // Set the length of this stream to 0
        _stream.SetLength( 0 );

        // Write to the beginning of the stream
        _stream.Position = 0;

        _memoryStream.WriteTo( _stream );
        _memoryStream.Flush();
      }
    }
    

开发者ID:xceedsoftware,项目名称:DocX,代码行数:91,代码来源:DocX.cs

在WriteToFileOrStream()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例2 - FilesAreBufferedAndCanBeFlushed()

    using System.IO;

        [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Runners))]
        public void FilesAreBufferedAndCanBeFlushed(FileSystemRunner fileSystem, string parentFolder)
        {
            string filename = Path.Combine(parentFolder, "FilesAreBufferedAndCanBeFlushed");
            string filePath = this.Enlistment.GetVirtualPathTo(filename);

            byte[] buffer = System.Text.Encoding.ASCII.GetBytes("Some test data");

            using (FileStream writeStream = File.Open(filePath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                writeStream.Write(buffer, 0, buffer.Length);

                using (FileStream readStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    readStream.Length.ShouldEqual(0);
                    writeStream.Flush();
                    readStream.Length.ShouldEqual(buffer.Length);

                    byte[] readBuffer = new byte[buffer.Length];
                    readStream.Read(readBuffer, 0, readBuffer.Length).ShouldEqual(readBuffer.Length);
                    readBuffer.ShouldMatchInOrder(buffer);
                }
            }

            fileSystem.DeleteFile(filePath);
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:BasicFileSystemTests.cs

在FilesAreBufferedAndCanBeFlushed()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例3 - WriteAllEntries()

    using System.IO;

        private void WriteAllEntries(uint version, bool isFinal)
        {
            try
            {
                using (Stream indexStream = new FileStream(this.indexLockPath, FileMode.Create, FileAccess.Write, FileShare.None))
                using (BinaryWriter writer = new BinaryWriter(indexStream))
                {
                    writer.Write(IndexHeader);
                    writer.Write(EndianHelper.Swap(version));
                    writer.Write((uint)0); // Number of entries placeholder

                    uint lastStringLength = 0;
                    LsTreeEntry entry;
                    while (this.entryQueue.TryTake(out entry, Timeout.Infinite))
                    {
                        this.WriteEntry(writer, version, entry.Sha, entry.Filename, ref lastStringLength);
                    }

                    // Update entry count
                    writer.BaseStream.Position = EntryCountOffset;
                    writer.Write(EndianHelper.Swap(this.entryCount));
                    writer.Flush();
                }

                this.AppendIndexSha();
                if (isFinal)
                {
                    this.ReplaceExistingIndex();
                }
            }
            catch (Exception e)
            {
                this.tracer.RelatedError("Failed to generate index: {0}", e.ToString());
                this.HasFailures = true;
            }
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:38,代码来源:GitIndexGenerator.cs

在WriteAllEntries()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例4 - TryWriteTempFile()

    using System.IO;

        public virtual bool TryWriteTempFile(
            ITracer tracer,
            Stream source,
            string tempFilePath,
            out long fileLength,
            out Task flushTask,
            bool throwOnError = false)
        {
            fileLength = 0;
            flushTask = null;
            try
            {
                Stream fileStream = null;

                try
                {
                    fileStream = this.fileSystem.OpenFileStream(
                        tempFilePath,
                        FileMode.OpenOrCreate,
                        FileAccess.Write,
                        FileShare.Read,
                        callFlushFileBuffers: false); // Any flushing to disk will be done asynchronously

                    StreamUtil.CopyToWithBuffer(source, fileStream);
                    fileLength = fileStream.Length;

                    if (this.Enlistment.FlushFileBuffersForPacks)
                    {
                        // Flush any data buffered in FileStream to the file system
                        fileStream.Flush();

                        // FlushFileBuffers using FlushAsync
                        // Do this last to ensure that the stream is not being accessed after it's been disposed
                        flushTask = fileStream.FlushAsync().ContinueWith((result) => fileStream.Dispose());
                    }
                }
                finally
                {
                    if (flushTask == null && fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }

                this.ValidateTempFile(tempFilePath, tempFilePath);
            }
            catch (Exception ex)
            {
                if (flushTask != null)
                {
                    flushTask.Wait();
                    flushTask = null;
                }

                this.CleanupTempFile(this.Tracer, tempFilePath);

                if (tracer != null)
                {
                    EventMetadata metadata = CreateEventMetadata(ex);
                    metadata.Add("tempFilePath", tempFilePath);
                    tracer.RelatedWarning(metadata, $"{nameof(this.TryWriteTempFile)}: Exception caught while writing temp file", Keywords.Telemetry);
                }

                if (throwOnError)
                {
                    throw;
                }
                else
                {
                    return false;
                }
            }

            return true;
        }
    

开发者ID:microsoft,项目名称:VFSForGit,代码行数:77,代码来源:GitObjects.cs

在TryWriteTempFile()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例5 - SaveFileForCompression()

    using System.IO;

        private void SaveFileForCompression(bool Compress, string[] fileNames, ICompressionFormat compressionFormat)
        {
            if (fileNames.Length == 0)
                return;

            string ext = Compress ? ".comp" : "";
            if (compressionFormat.Extension.Length > 0 && Compress)
                ext = compressionFormat.Extension[0].Replace("*", string.Empty);

            List failedFiles = new List();
            if (fileNames.Length > 1)
            {
                FolderSelectDialog ofd = new FolderSelectDialog();
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    foreach (var file in fileNames)
                    {
                        string name = Path.GetFileName(file);
                        name = name.Count(c => c == '.') > 1 && !Compress ? name.Remove(name.LastIndexOf('.')) : name;
                        using (var data = new FileStream(file, FileMode.Open, FileAccess.Read))
                        {
                            try
                            {
                                Stream stream;
                                if (Compress)
                                    stream = compressionFormat.Compress(data);
                                else
                                {
                                    compressionFormat.Identify(data, file);
                                    stream = compressionFormat.Decompress(data);
                                }

                                if (stream != null)
                                {
                                    stream.ExportToFile($"{ofd.SelectedPath}/{name}{ext}");
                                    stream.Flush();
                                    stream.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                                failedFiles.Add($"{file} \n\n {ex} \n\n");
                            }
                        }
                    }

                    if (failedFiles.Count > 0)
                    {
                        string action = Compress ? "compress" : "decompress";
                        STErrorDialog.Show($"Some files failed to {action}! See detail list of failed files.", "Switch Toolbox",
                            string.Join("\n", failedFiles.ToArray()));
                    }
                    else
                        MessageBox.Show("Files batched successfully!");
                }
            }
            else
            {
                SaveFileDialog sfd = new SaveFileDialog();
                string name = Path.GetFileName(fileNames[0]);
                sfd.FileName = name + ext;
                sfd.Filter = "All files(*.*)|*.*";

                Cursor.Current = Cursors.Default;
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (var data = new FileStream(fileNames[0], FileMode.Open, FileAccess.Read))
                        {
                            Stream stream;
                            if (Compress)
                                stream = compressionFormat.Compress(data);
                            else
                            {
                                compressionFormat.Identify(data, fileNames[0]);
                                stream = compressionFormat.Decompress(data);
                            }

                            if (stream != null)
                            {
                                stream.ExportToFile(sfd.FileName);
                                stream.Flush();
                                stream.Close();

                                MessageBox.Show($"File has been saved to {sfd.FileName}", "Save Notification");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        string action = Compress ? "compress" : "decompress";
                        STErrorDialog.Show($"Failed to {action}! See details for info.", "Switch Toolbox", ex.ToString());
                    }
                }
            }
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:99,代码来源:CompressionMenus.cs

在SaveFileForCompression()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例6 - SaveFileFormat()

    using System.IO;
        /// 
        /// Saves the  as a file from the given 
        /// 
        /// The format instance of the file being saved
        /// The name of the file
        /// The Alignment used for compression. Used for Yaz0 compression type. 
        /// Toggle for showing compression dialog
        /// 
        public static void SaveFileFormat(IFileFormat FileFormat, string FileName, bool EnableDialog = true, string DetailsLog = "")
        {
            //These always get created on loading a file,however not on creating a new file
            if (FileFormat.IFileInfo == null)
                throw new System.NotImplementedException("Make sure to impliment a IFileInfo instance if a format is being created!");

            Cursor.Current = Cursors.WaitCursor;
            FileFormat.FilePath = FileName;

            string compressionLog = "";
            if (FileFormat.IFileInfo.FileIsCompressed || FileFormat.IFileInfo.InArchive
                || Path.GetExtension(FileName) == ".szs" || Path.GetExtension(FileName) == ".sbfres"
                || Path.GetExtension(FileName) == ".mc")
            {
                //Todo find more optmial way to handle memory with files in archives
                //Also make compression require streams
                var mem = new System.IO.MemoryStream();
                FileFormat.Save(mem);
                mem =  new System.IO.MemoryStream(mem.ToArray());

                FileFormat.IFileInfo.DecompressedSize = (uint)mem.Length;

                var finalStream = CompressFileFormat(
                    FileFormat.IFileInfo.FileCompression,
                    mem,
                    FileFormat.IFileInfo.FileIsCompressed,
                    FileFormat.IFileInfo.Alignment,
                    FileName,
                    EnableDialog);

                compressionLog = finalStream.Item2;
                Stream compressionStream = finalStream.Item1;

                FileFormat.IFileInfo.CompressedSize = (uint)compressionStream.Length;
                compressionStream.ExportToFile(FileName);

                DetailsLog += "\n" + SatisfyFileTables(FileFormat, FileName, compressionStream,
                                    FileFormat.IFileInfo.DecompressedSize,
                                    FileFormat.IFileInfo.CompressedSize,
                                    FileFormat.IFileInfo.FileIsCompressed);

                compressionStream.Flush();
                compressionStream.Close();
            }
            else
            {
                //Check if a stream is active and the file is beinng saved to the same opened file
                if (FileFormat is ISaveOpenedFileStream && FileFormat.FilePath == FileName && File.Exists(FileName))
                {
                    string savedPath = Path.GetDirectoryName(FileName);
                    string tempPath = Path.Combine(savedPath, "tempST.bin");

                    //Save a temporary file first to not disturb the opened file
                    using (var fileStream = new FileStream(tempPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);
                        FileFormat.Unload();

                        //After saving is done remove the existing file
                        File.Delete(FileName);

                        //Now move and rename our temp file to the new file path
                        File.Move(tempPath, FileName);

                        FileFormat.Load(File.OpenRead(FileName));

                        var activeForm = LibraryGUI.GetActiveForm();
                        if (activeForm != null && activeForm is ObjectEditor)
                            ((ObjectEditor)activeForm).ReloadArchiveFile(FileFormat);
                    }
                }
                else
                {
                    using (var fileStream = new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                    {
                        FileFormat.Save(fileStream);
                    }
                }
            }

            if (EnableDialog)
            {
                if (compressionLog != string.Empty)
                    MessageBox.Show($"File has been saved to {FileName}. Compressed time: {compressionLog}", "Save Notification");
                else
                    MessageBox.Show($"File has been saved to {FileName}", "Save Notification");
            }

            //   STSaveLogDialog.Show($"File has been saved to {FileName}", "Save Notification", DetailsLog);
            Cursor.Current = Cursors.Default;
        }
    

开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:100,代码来源:STFileSaver.cs

在SaveFileFormat()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例7 - SetHost()

    using System.IO;

        /// 
        /// 
        /// 
        /// 
        /// 空值表示删除对应的host记录
        /// 测试用
        public static void SetHost(string host, string ip, string hostsPath = null) {
            GetIp(host, out long position, hostsPath);
            if (position == -2) {
                File.WriteAllText(hostsPath, $"{ip} {host}");
                return;
            }
            if (string.IsNullOrEmpty(hostsPath)) {
                hostsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "drivers\\etc\\hosts");
            }
            //通常情况下这个文件是只读的,所以写入之前要取消只读
            File.SetAttributes(hostsPath, File.GetAttributes(hostsPath) & (~FileAttributes.ReadOnly));
            byte[] buffer = new byte[]{ };
            using (MemoryStream ms = new MemoryStream())
            using (StreamWriter sw = new StreamWriter(ms))
            using (FileStream fs = new FileStream(hostsPath, FileMode.OpenOrCreate, FileAccess.Read))
            using (StreamReader sr = new StreamReader(fs)) {
                bool writed = false;
                while (true) {
                    long p = sr.BaseStream.Position;
                    string line = sr.ReadLine();
                    if (p == position) {
                        if (!string.IsNullOrEmpty(ip)) {
                            sw.WriteLine($"{ip} {host}");
                        }
                        writed = true;
                    }
                    else {
                        sw.WriteLine(line);
                    }
                    if (sr.EndOfStream) {
                        break;
                    }
                }
                if (!writed) {
                    sw.WriteLine($"{ip} {host}");
                }
                sw.Flush();
                buffer = ms.ToArray();
            }
            File.WriteAllBytes(hostsPath, buffer);
        }
    

开发者ID:ntminer,项目名称:NtMiner,代码行数:49,代码来源:Hosts.cs

在SetHost()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

FileStream.Flush的代码示例8 - SerializeAllCsprojSubTypes()

    using System.IO;

        public static void SerializeAllCsprojSubTypes(object allCsProjSubTypes)
        {
            // If DbPath is not specify, do not save C# subtypes information
            if (string.IsNullOrEmpty(WinFormSubTypesDbPath))
                return;

            if (!Directory.Exists(WinFormSubTypesDbPath))
                Directory.CreateDirectory(WinFormSubTypesDbPath);

            string winFormSubTypesDbFullPath = GetWinFormSubTypeDbPath();

            using (Stream writeStream = new FileStream(winFormSubTypesDbFullPath, FileMode.Create, FileAccess.Write, FileShare.None))
            using (BinaryWriter binWriter = new BinaryWriter(writeStream))
            {
                string csprojSubTypesAsJson = System.Text.Json.JsonSerializer.Serialize(allCsProjSubTypes, GetCsprojSubTypesJsonSerializerOptions());
                binWriter.Write(csprojSubTypesAsJson);
                binWriter.Flush();
            }
        }
    

开发者ID:ubisoft,项目名称:Sharpmake,代码行数:21,代码来源:Util.cs

在SerializeAllCsprojSubTypes()方法中,FileStream的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

本文中的FileStream.Flush方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。