C# File.ToString的代码示例
通过代码示例来学习C# File.ToString方法
通过代码示例来学习编程是非常高效的。
1. 代码示例提供了一个具体而直观的学习环境,使初学者能够立即看到编程概念和语法的实际应用。
2. 通过分析和模仿现有的代码实例,初学者可以更好地理解编程逻辑和算法的工作原理。
3. 代码实例往往涵盖了多种编程技巧和最佳实践,通过学习和模仿这些实例,学习者可以逐步掌握如何编写高效、可读性强和可维护的代码。这对于初学者来说,是一种快速提升编程水平的有效途径。
File.ToString是C#的System.IO命名空间下中的一个方法, 小编为大家找了一些网络大拿们常见的代码示例,源码中的File.ToString() 已经帮大家高亮显示了,大家可以重点学习File.ToString() 方法的写法,从而快速掌握该方法的应用。
File.ToString的代码示例1 - TryDeleteFile()
using System.IO; protected bool TryDeleteFile(ITracer tracer, string fileName) { try { File.Delete(fileName); } catch (Exception e) { tracer.RelatedError("Failed to delete file {0}: {1}", fileName, e.ToString()); return true; } return true; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:16,代码来源:DiskLayoutUpgrade.cs
在TryDeleteFile()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例2 - CheckEnableGitStatusCacheTokenFile()
using System.IO; ///
/// To work around a behavior in ProjFS where notification masks on files that have been opened in virtualization instance are not invalidated /// when the virtualization instance is restarted, GVFS waits until after there has been a reboot before enabling the GitStatusCache. /// GVFS.Service signals that there has been a reboot since installing a version of GVFS that supports the GitStatusCache via /// the existence of the file "EnableGitStatusCacheToken.dat" in {CommonApplicationData}\GVFS\GVFS.Service /// (i.e. ProgramData\GVFS\GVFS.Service\EnableGitStatusCacheToken.dat on Windows). /// private void CheckEnableGitStatusCacheTokenFile() { try { string statusCacheVersionTokenPath = Path.Combine(GVFSPlatform.Instance.GetSecureDataRootForGVFSComponent(GVFSConstants.Service.ServiceName), GVFSConstants.GitStatusCache.EnableGitStatusCacheTokenFile); if (File.Exists(statusCacheVersionTokenPath)) { this.tracer.RelatedInfo($"CheckEnableGitStatusCache: EnableGitStatusCacheToken file already exists at {statusCacheVersionTokenPath}."); return; } DateTime lastRebootTime = NativeMethods.GetLastRebootTime(); // GitStatusCache was included with GVFS on disk version 16. The 1st time GVFS that is at or above on disk version // is installed, it will write out a file indicating that the installation is "OnDiskVersion16Capable". // We can query the properties of this file to get the installation time, and compare this with the last reboot time for // this machine. string fileToCheck = Path.Combine(Configuration.AssemblyPath, GVFSConstants.InstallationCapabilityFiles.OnDiskVersion16CapableInstallation); if (File.Exists(fileToCheck)) { DateTime installTime = File.GetCreationTime(fileToCheck); if (lastRebootTime > installTime) { this.tracer.RelatedInfo($"CheckEnableGitStatusCache: Writing out EnableGitStatusCacheToken file. GVFS installation time: {installTime}, last Reboot time: {lastRebootTime}."); File.WriteAllText(statusCacheVersionTokenPath, string.Empty); } else { this.tracer.RelatedInfo($"CheckEnableGitStatusCache: Not writing EnableGitStatusCacheToken file - machine has not been rebooted since OnDiskVersion16Capable installation. GVFS installation time: {installTime}, last reboot time: {lastRebootTime}"); } } else { this.tracer.RelatedError($"Unable to determine GVFS installation time: {fileToCheck} does not exist."); } } catch (Exception ex) { // Do not crash the service if there is an error here. Service is still healthy, but we // might not create file indicating that it is OK to use GitStatusCache. this.tracer.RelatedError($"{nameof(this.CheckEnableGitStatusCacheTokenFile)}: Unable to determine GVFS installation time or write EnableGitStatusCacheToken file due to exception. Exception: {ex.ToString()}"); } }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:53,代码来源:GVFSService.Windows.cs
在CheckEnableGitStatusCacheTokenFile()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例3 - TryFixIssues()
using System.IO; ///
/// Fixes the HEAD using the reflog to find the last SHA. /// We detach HEAD as a side-effect of repair. /// public override FixResult TryFixIssues(Listmessages) { string error; RefLogEntry refLog; if (!TryReadLastRefLogEntry(this.Enlistment, GVFSConstants.DotGit.HeadName, out refLog, out error)) { this.Tracer.RelatedError(error); messages.Add(error); return FixResult.Failure; } try { string refPath = Path.Combine(this.Enlistment.WorkingDirectoryBackingRoot, GVFSConstants.DotGit.Head); File.WriteAllText(refPath, refLog.TargetSha); } catch (IOException ex) { EventMetadata metadata = new EventMetadata(); this.Tracer.RelatedError(metadata, "Failed to write HEAD: " + ex.ToString()); return FixResult.Failure; } this.Tracer.RelatedEvent( EventLevel.Informational, "MovedHead", new EventMetadata { { "DestinationCommit", refLog.TargetSha } }); messages.Add("As a result of the repair, 'git status' will now complain that HEAD is detached"); messages.Add("You can fix this by creating a branch using 'git checkout -b '"); return FixResult.Success; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:42,代码来源:GitHeadRepairJob.cs
在TryFixIssues()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例4 - PerformPreMountValidation()
using System.IO; private bool PerformPreMountValidation(ITracer tracer, GVFSEnlistment enlistment, out string mountExecutableLocation, out string errorMessage) { errorMessage = string.Empty; mountExecutableLocation = string.Empty; // We have to parse these parameters here to make sure they are valid before // handing them to the background process which cannot tell the user when they are bad EventLevel verbosity; Keywords keywords; this.ParseEnumArgs(out verbosity, out keywords); mountExecutableLocation = Path.Combine(ProcessHelper.GetCurrentProcessLocation(), GVFSPlatform.Instance.Constants.MountExecutableName); if (!File.Exists(mountExecutableLocation)) { errorMessage = $"Could not find {GVFSPlatform.Instance.Constants.MountExecutableName}. You may need to reinstall GVFS."; return false; } GitProcess git = new GitProcess(enlistment); if (!git.IsValidRepo()) { errorMessage = "The .git folder is missing or has invalid contents"; return false; } try { GitIndexProjection.ReadIndex(tracer, Path.Combine(enlistment.WorkingDirectoryBackingRoot, GVFSConstants.DotGit.Index)); } catch (Exception e) { EventMetadata metadata = new EventMetadata(); metadata.Add("Exception", e.ToString()); tracer.RelatedError(metadata, "Index validation failed"); errorMessage = "Index validation failed, run 'gvfs repair' to repair index."; return false; } if (!GVFSPlatform.Instance.FileSystem.IsFileSystemSupported(enlistment.EnlistmentRoot, out string error)) { errorMessage = $"FileSystem unsupported: {error}"; return false; } return true; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:49,代码来源:MountVerb.cs
在PerformPreMountValidation()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例5 - TryRenameToBackupFile()
using System.IO; protected bool TryRenameToBackupFile(string filePath, out string backupPath, List
messages) { backupPath = filePath + BackupExtension; try { File.Move(filePath, backupPath); this.Tracer.RelatedEvent(EventLevel.Informational, "FileMoved", new EventMetadata { { "SourcePath", filePath }, { "DestinationPath", backupPath } }); } catch (Exception e) { messages.Add("Failed to back up " + filePath + " to " + backupPath); this.Tracer.RelatedError("Exception while moving " + filePath + " to " + backupPath + ": " + e.ToString()); return false; } return true; }
开发者ID:microsoft,项目名称:VFSForGit,代码行数:19,代码来源:RepairJob.cs
在TryRenameToBackupFile()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例6 - BuildWxs()
using System.IO; ///
/// Builds the WiX source file (*.wxs) from the specified /// The project. ///instance. /// public static string BuildWxs(Bundle project) { lock (typeof(Compiler)) { if (Compiler.ClientAssembly.IsEmpty()) Compiler.ClientAssembly = Compiler.FindClientAssemblyInCallStack(); project.Validate(); lock (Compiler.AutoGeneration.WxsGenerationSynchObject) { var oldAlgorithm = AutoGeneration.CustomIdAlgorithm; try { project.ResetAutoIdGeneration(supressWarning: false); AutoGeneration.CustomIdAlgorithm = project.CustomIdAlgorithm ?? AutoGeneration.CustomIdAlgorithm; string file = IO.Path.GetFullPath(IO.Path.Combine(project.OutDir, project.OutFileName) + ".wxs"); if (IO.File.Exists(file)) IO.File.Delete(file); string extraNamespaces = project.WixNamespaces.Distinct() .Select(x => x.StartsWith("xmlns:") ? x : "xmlns:" + x) .ConcatItems(" "); var wix3Namespace = "http://schemas.microsoft.com/wix/2006/wi"; var wix4Namespace = "http://wixtoolset.org/schemas/v4/wxs"; var wixNamespace = Compiler.IsWix4 ? wix4Namespace : wix3Namespace; var doc = XDocument.Parse( @" " + $" "); doc.Root.Add(project.ToXml()); AutoElements.NormalizeFilePaths(doc, project.SourceBaseDir, EmitRelativePaths); project.InvokeWixSourceGenerated(doc); AutoElements.ExpandCustomAttributes(doc, project); if (WixSourceGenerated != null) WixSourceGenerated(doc); var xmlEncoding = Encoding.UTF8; string xml = ""; using (IO.StringWriter sw = new StringWriterWithEncoding(xmlEncoding)) { doc.Save(sw, SaveOptions.None); xml = sw.ToString(); } //of course you can use XmlTextWriter.WriteRaw but this is just a temporary quick'n'dirty solution //http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2657663&SiteID=1 xml = xml.Replace("xmlns=\"\"", ""); DefaultWixSourceFormatedHandler(ref xml); project.InvokeWixSourceFormated(ref xml); if (WixSourceFormated != null) WixSourceFormated(ref xml); using (var sw = new IO.StreamWriter(file, false, xmlEncoding)) sw.WriteLine(xml); Compiler.OutputWriteLine("\n----------------------------------------------------------\n"); Compiler.OutputWriteLine("Wix project file has been built: " + file + "\n"); project.InvokeWixSourceSaved(file); if (WixSourceSaved != null) WixSourceSaved(file); return file; } finally { AutoGeneration.CustomIdAlgorithm = oldAlgorithm; project.ResetAutoIdGeneration(supressWarning: true); } } } }
开发者ID:oleg-shilo,项目名称:wixsharp,代码行数:94,代码来源:Compiler.Bootstrapper.cs
在BuildWxs()方法中,File的代码示例类中的ToString的代码示例方法一共出现了1次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例7 - Upload()
using System.IO; private void Upload() { if (string.IsNullOrEmpty(_settings.ApiKey)) { MessageBox.Show(LocalizationHelper.Base.UploadForm_NoApiKey, LocalizationHelper.Base.UploadForm_InvalidKey, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (_settings.ApiKey.Length != 64) { MessageBox.Show(LocalizationHelper.Base.UploadForm_InvalidLength, LocalizationHelper.Base.UploadForm_InvalidKey, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } ChangeStatus(LocalizationHelper.Base.Message_Init); _client = new RestClient("https://www.virustotal.com"); if (!File.Exists(_fileName)) { throw new FileNotFoundException(); } ChangeStatus(LocalizationHelper.Base.Message_Check); var reportRequest = new RestRequest("vtapi/v2/file/report", Method.Post); reportRequest.AddParameter("apikey", _settings.ApiKey); reportRequest.AddParameter("resource", Utils.GetMD5(_fileName)); var reportResponse = _client.Execute(reportRequest); var reportContent = reportResponse.Content; dynamic reportJson = JsonConvert.DeserializeObject(reportContent); try { var reportLink = reportJson.permalink.ToString(); Process.Start(reportLink); if (_settings.DirectUpload) CloseWindow(); } catch (RuntimeBinderException) { // Json does not contain permalink which means it's a new file (or the request failed) ChangeStatus(LocalizationHelper.Base.Message_Upload); var scanRequest = new RestRequest("vtapi/v2/file/scan", Method.Post); scanRequest.AddParameter("apikey", _settings.ApiKey); scanRequest.AddFile("file", _fileName); var scanResponse = _client.Execute(scanRequest); var scanContent = scanResponse.Content; // TODO: check for HTML (file too large) dynamic scanJson = JsonConvert.DeserializeObject(scanContent); try { string scanLink = scanJson.permalink.ToString(); // An example link can look like this: // https://www.virustotal.com/gui/file/
/detection/ // If we don't remove the the scanid, then it will fail on new files since the scan did not finish // Removing it like this will show the analysis progress for new files scanLink = scanLink.Remove(scanLink.IndexOf("/detection")); Process.Start(scanLink); if (_settings.DirectUpload) CloseWindow(); } catch (Exception) { // Response does not contain permalink so it failed ChangeStatus(LocalizationHelper.Base.Message_NoLink); Finish(false); return; } } Finish(true); }
开发者ID:SamuelTulach,项目名称:VirusTotalUploader,代码行数:78,代码来源:UploadForm.cs
在Upload()方法中,File的代码示例类中的ToString的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
File.ToString的代码示例8 - 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的代码示例类中的ToString的代码示例方法一共出现了2次, 见黄色背景高亮显示的地方,欢迎大家点赞
本文中的File.ToString方法示例由csref.cn整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。