C# File.Flush的代码示例

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

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


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

File.Flush的代码示例1 - 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()方法中,File的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Flush的代码示例2 - WriteExtraSkinningInfo()

    using System.IO;

        //Extra skin data based on https://github.com/Sage-of-Mirrors/SuperBMD/blob/ce1061e9b5f57de112f1d12f6459b938594664a0/SuperBMDLib/source/Model.cs#L193
        //Todo this doesn't quite work yet
        //Need to adjust all mesh name IDs so they are correct
        private void WriteExtraSkinningInfo(string FileName, Scene outScene, List Meshes)
        {
            StreamWriter test = new StreamWriter(FileName + ".tmp");
            StreamReader dae = File.OpenText(FileName);

            int geomIndex = 0;
            while (!dae.EndOfStream)
            {
                string line = dae.ReadLine();

                /* if (line == "  ")
                 {
                     AddControllerLibrary(outScene, test);
                     test.WriteLine(line);
                     test.Flush();
                 }
                 else if (line.Contains(".Flush();

                     string[] testLn = line.Split('\"');
                     string name = testLn[3];

                     string jointLine = line.Replace(">", $" sid=\"{ name }\" type=\"JOINT\">");
                     test.WriteLine(jointLine);
                     test.Flush();
                 }
                 else if (line.Contains(""))
                 {
                     foreach (Mesh mesh in outScene.Meshes)
                     {
                         test.WriteLine($"      ");

                         test.WriteLine($"       ");
                         test.WriteLine("        #skeleton_root");
                         test.WriteLine("        ");
                         test.WriteLine("         ");
                         test.WriteLine($"          ");
                         test.WriteLine("         ");
                         test.WriteLine("        ");
                         test.WriteLine("       ");

                         test.WriteLine("      ");
                         test.Flush();
                     }

                     test.WriteLine(line);
                     test.Flush();
                 }*/
                if (line.Contains(" ");
                    test.Flush();

                    geomIndex++;
                }
                else
                {
                    test.WriteLine(line);
                    test.Flush();
                }

                /*    else if (line.Contains("", "");
                        test.WriteLine(matLine);
                        test.Flush();
                    }*/

            }

            test.Close();
            dae.Close();

            File.Copy(FileName + ".tmp", FileName, true);
            File.Delete(FileName + ".tmp");
        }
    

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

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

File.Flush的代码示例3 - 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()方法中,File的代码示例类中的Flush的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Flush的代码示例4 - 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()方法中,File的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Flush的代码示例5 - DataReaderTest()

    using System.IO;

        [Test]
        public static void DataReaderTest()
        {
            string csv = @"Id, Name, Address2
1, Tom,
2, Mark,";

            var dr = ChoCSVReader.LoadText(csv).WithFirstLineHeader().AsDataReader();

            using (var sw = new StreamWriter(File.OpenWrite(FileNameDataReaderTestTestCSV)))
            {
                using (var csvWriter = new ChoCSVWriter(sw)
                    .WithFirstLineHeader()
                    //.Configure(c => c.UseNestedKeyFormat = false)
                    )
                {
                    csvWriter.WriteDataReader(dr);
                    sw.Flush();
                }
            }

            FileAssert.AreEqual(FileNameDataReaderTestExpectedCSV, FileNameDataReaderTestTestCSV);
        }
    

开发者ID:Cinchoo,项目名称:ChoETL,代码行数:25,代码来源:Program.cs

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

File.Flush的代码示例6 - CreateFile()

    using System.IO;

        protected string CreateFile(DirectoryInfo dInfo, string fileName)
        {
            int lineCount = 10;
            string fullName = dInfo == null ? fileName : dInfo.FullName + Path.DirectorySeparatorChar + fileName;

            using (StreamWriter writer = new StreamWriter(File.Create(fullName)))
            {
                for (int i = 1; i <= lineCount; ++i)
                {
                    writer.WriteLine("Line number " + i.ToString("D3") + " of File " + fullName);
                }

                writer.Flush();
            }

            return fullName;
        }
    

开发者ID:zarunbal,项目名称:LogExpert,代码行数:19,代码来源:RolloverHandlerTestBase.cs

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

File.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()方法中,File的代码示例类中的Flush的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞

File.Flush的代码示例8 - VerifyResults()

    using System.IO;

        private void VerifyResults(FileGeneratorTestHelper testHelper)
        {
            testHelper.Flush();

            string tmpFile1 = Path.GetTempFileName();
            string tmpFile2 = Path.GetTempFileName();
            try
            {
                // Check that generated content is different than default content of tmp file(empty)
                var fileInfo1 = new FileInfo(tmpFile1);
                var fileInfo2 = new FileInfo(tmpFile2);

                Assert.IsTrue(testHelper.Generator.IsFileDifferent(fileInfo1));
                Assert.IsTrue(testHelper.Generator.IsFileDifferent(fileInfo2));

                // Write the file using reference stream
                Assert.IsTrue(Util.FileWriteIfDifferentInternal(fileInfo1, testHelper.Stream, true));
                fileInfo1.Refresh();

                // Using second file to write a file using generator.
                Assert.IsTrue(testHelper.Generator.FileWriteIfDifferent(fileInfo2, true));
                fileInfo2.Refresh();

                // Verify that generator content is the same.
                Assert.IsFalse(testHelper.Generator.IsFileDifferent(fileInfo1));

                // Verify that written file is identical to stream
                Assert.IsFalse(Util.IsFileDifferent(fileInfo2, testHelper.Stream));

                // Read the two files and verify that they are identical
                var contentFile1 = File.ReadAllBytes(tmpFile1);
                var contentFile2 = File.ReadAllBytes(tmpFile2);
                ReadOnlySpan span1 = new ReadOnlySpan(contentFile1);
                ReadOnlySpan span2 = new ReadOnlySpan(contentFile2);
                Assert.IsTrue(span1.SequenceEqual(span2));
            }
            finally
            {
                File.Delete(tmpFile1);
                File.Delete(tmpFile2);
            }
        }
    

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

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

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