C# File.Create的代码示例
通过代码示例来学习C# File.Create方法
通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。
File.Create是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.Create() 已经帮大家高亮显示了,大家可以重点学习File.Create() 方法的写法,从而快速掌握该方法的应用。
File.Create的代码示例1 - NewFileAttributesAreUpdated()
using System.IO; [TestCaseSource(typeof(FileRunnersAndFolders), nameof(FileRunnersAndFolders.Folders))] public void NewFileAttributesAreUpdated(string parentFolder) { string filename = Path.Combine(parentFolder, "FileAttributesAreUpdated"); FileSystemRunner fileSystem = FileSystemRunner.DefaultRunner; string virtualFile = this.Enlistment.GetVirtualPathTo(filename); virtualFile.ShouldNotExistOnDisk(fileSystem); File.Create(virtualFile).Dispose(); virtualFile.ShouldBeAFile(fileSystem); // Update defaults. FileInfo is not batched, so each of these will create a separate Open-Update-Close set. FileInfo before = new FileInfo(virtualFile); DateTime testValue = DateTime.Now + TimeSpan.FromDays(1); before.CreationTime = testValue; before.LastAccessTime = testValue; before.LastWriteTime = testValue; before.Attributes = FileAttributes.Hidden; // FileInfo caches information. We can refresh, but just to be absolutely sure... virtualFile.ShouldBeAFile(fileSystem).WithInfo(testValue, testValue, testValue, FileAttributes.Hidden); File.Delete(virtualFile); virtualFile.ShouldNotExistOnDisk(fileSystem); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:BasicFileSystemTests.cs
在NewFileAttributesAreUpdated()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例2 - CanReadWriteAFileInParallel()
using System.IO; [TestCaseSource(typeof(FileSystemRunner), nameof(FileSystemRunner.Runners))] [Order(3)] public void CanReadWriteAFileInParallel(FileSystemRunner fileSystem) { string fileName = @"CanReadWriteAFileInParallel"; string virtualPath = this.Enlistment.GetVirtualPathTo(fileName); // Create the file new each time. virtualPath.ShouldNotExistOnDisk(fileSystem); File.Create(virtualPath).Dispose(); bool keepRunning = true; Thread[] threads = new Thread[4]; StringBuilder[] fileContents = new StringBuilder[4]; // Writer fileContents[0] = new StringBuilder(); threads[0] = new Thread(() => { DateTime start = DateTime.Now; Random r = new Random(0); // Seeded for repeatability while ((DateTime.Now - start).TotalSeconds < 2.5) { string newChar = r.Next(10).ToString(); fileSystem.AppendAllText(virtualPath, newChar); fileContents[0].Append(newChar); Thread.Yield(); } keepRunning = false; }); // Readers for (int i = 1; i < threads.Length; ++i) { int myIndex = i; fileContents[i] = new StringBuilder(); threads[i] = new Thread(() => { using (Stream readStream = File.Open(virtualPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (StreamReader reader = new StreamReader(readStream, true)) { while (keepRunning) { Thread.Yield(); fileContents[myIndex].Append(reader.ReadToEnd()); } // Catch the last write that might have escaped us fileContents[myIndex].Append(reader.ReadToEnd()); } }); } foreach (Thread thread in threads) { thread.Start(); } foreach (Thread thread in threads) { thread.Join(); } for (int i = 1; i < threads.Length; ++i) { fileContents[i].ToString().ShouldEqual(fileContents[0].ToString()); } fileSystem.DeleteFile(virtualPath); }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:73,代码来源:MultithreadedReadWriteTests.cs
在CanReadWriteAFileInParallel()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例3 - OpenForWrite()
using System.IO; private static SafeFileHandle OpenForWrite(ITracer tracer, string fileName) { SafeFileHandle handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero); if (handle.IsInvalid) { // If we get a access denied, try reverting the acls to defaults inherited by parent if (Marshal.GetLastWin32Error() == AccessDeniedWin32Error) { tracer.RelatedEvent( EventLevel.Warning, "FailedOpenForWrite", new EventMetadata { { TracingConstants.MessageKey.WarningMessage, "Received access denied. Attempting to delete." }, { "FileName", fileName } }); File.SetAttributes(fileName, FileAttributes.Normal); File.Delete(fileName); handle = CreateFile(fileName, FileAccess.Write, FileShare.None, IntPtr.Zero, FileMode.Create, FileAttributes.Normal, IntPtr.Zero); } } return handle; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:28,代码来源:NativeMethods.cs
在OpenForWrite()方法中,File的代码示例类中的Create的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例4 - RunBeforeAnyTests()
using System.IO; private static void RunBeforeAnyTests() { if (GVFSTestConfig.ReplaceInboxProjFS) { ProjFSFilterInstaller.ReplaceInboxProjFS(); } GVFSServiceProcess.InstallService(); string serviceProgramDataDir = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.Create), "GVFS", "ProgramData", "GVFS.Service"); string statusCacheVersionTokenPath = Path.Combine( serviceProgramDataDir, "EnableGitStatusCacheToken.dat"); if (!File.Exists(statusCacheVersionTokenPath)) { Directory.CreateDirectory(serviceProgramDataDir); File.WriteAllText(statusCacheVersionTokenPath, string.Empty); } }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:26,代码来源:Program.cs
在RunBeforeAnyTests()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例5 - GetMD5()
using System.IO; public static string GetMD5(string file) { using (var md5 = MD5.Create()) { using (var stream = File.OpenRead(file)) { var hashBytes = md5.ComputeHash(stream); var sb = new StringBuilder(); foreach (var t in hashBytes) { sb.Append(t.ToString("X2")); } return sb.ToString(); } } }
开发者ID:SamuelTulach,项目名称:VirusTotalUploader,代码行数:17,代码来源:Utils.cs
在GetMD5()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例6 - Main()
using System.IO; static void Main(string[] args) { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); execDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location); folderDir = execDirectory; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; var client = new GitHubClient(new ProductHeaderValue("ST_UpdateTool")); GetReleases(client).Wait(); string versionTxt = Path.Combine(execDirectory, "Version.txt"); if (!File.Exists(versionTxt)) File.Create(versionTxt); string[] versionInfo = File.ReadLines(versionTxt).ToArray(); string ProgramVersion = ""; string CompileDate = ""; string CommitInfo = ""; if (versionInfo.Length >= 3) { ProgramVersion = versionInfo[0]; CompileDate = versionInfo[1]; CommitInfo = versionInfo[2]; } foreach (string arg in args) { switch (arg) { case "-d": case "--download": Download(CompileDate); break; case "-i": case "--install": Install(); break; case "-b": case "--boot": Boot(); Environment.Exit(0); break; case "-e": case "--exit": Environment.Exit(0); break; } } Console.Read(); }
开发者ID:KillzXGaming,项目名称:Switch-Toolbox,代码行数:55,代码来源:Program.cs
在Main()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例7 - SaveFileFormat()
using System.IO; ///
/// Saves the /// 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 ///as a file from the given /// 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的代码示例类中的Create的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.Create的代码示例8 - Get()
using System.IO; ///
/// Gets a specified attachment frame from the specified tag, /// optionally creating it if it does not exist. /// /// /// Aobject to search in. /// /// /// A specifying the description to /// match. /// /// /// A specifying the picture type /// to match. /// /// /// A specifying whether or not to create /// and add a new frame to the tag if a match is not found. /// /// /// A ///object containing /// the matching frame, or if a match /// wasn't found and is . /// /// public static AttachmentFrame Get (Tag tag, string description, PictureType type, bool create) { AttachmentFrame att; foreach (Frame frame in tag.GetFramesSets a cover image with a description. Because ///is used, if /// the program is called again with the same audio file and /// desciption, the picture will be overwritten with the new /// one. /// using TagLib; /// using TagLib.Id3v2; /// /// public static class SetId3v2Cover /// { /// public static void Main (string [] args) /// { /// if (args.Length != 3) /// throw new ApplicationException ( /// "USAGE: SetId3v2Cover.exe AUDIO_FILE PICTURE_FILE DESCRIPTION"); /// /// // Create the file. Can throw file to TagLib# exceptions. /// File file = File.Create (args [0]); /// /// // Get or create the ID3v2 tag. /// TagLib.Id3v2.Tag tag = file.GetTag (TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; /// if (tag == null) /// throw new ApplicationException ("File does not support ID3v2 tags."); /// /// // Create a picture. Can throw file related exceptions. /// TagLib.Picture picture = TagLib.Picture.CreateFromPath (args [1]); /// /// // Get or create the picture frame. /// AttachedPictureFrame frame = AttachedPictureFrame.Get ( /// tag, args [2], PictureType.FrontCover, true); /// /// // Set the data from the picture. /// frame.MimeType = picture.MimeType; /// frame.Data = picture.data; /// /// // Save the file. /// file.Save (); /// } /// } ///
///()) { att = frame as AttachmentFrame; if (att == null) continue; if (description != null && att.Description != description) continue; if (type != PictureType.Other && att.Type != type) continue; return att; } if (!create) return null; att = new AttachmentFrame { Description = description, Type = type }; tag.AddFrame (att); return att; }
开发者ID:mono,项目名称:taglib-sharp,代码行数:100,代码来源:AttachmentFrame.cs
在Get()方法中,File的代码示例类中的Create的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
本文中的File.Create方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。