C# Path.GetRandomFileName的代码示例

通过代码示例来学习C# Path.GetRandomFileName方法

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


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

Path.GetRandomFileName的代码示例1 - New()

    using System.IO;

        public void New()
        {
            tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            int tries = 1;
            var baseFolder = tempFolder;
            while (Directory.Exists(tempFolder) && tries < 3)
            {
                tempFolder = $"{baseFolder}_{tries}";
                tries++;
            }
            if (tries >= 3)
                throw new Exception("Failed to create temporary folder");

            Directory.CreateDirectory(tempFolder);
        }
    

开发者ID:emoose,项目名称:DLSSTweaks,代码行数:17,代码来源:Utility.cs

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

Path.GetRandomFileName的代码示例2 - WriteTempPackFile()

    using System.IO;

        public virtual string WriteTempPackFile(Stream stream)
        {
            string fileName = Path.GetRandomFileName();
            string fullPath = Path.Combine(this.Enlistment.GitPackRoot, fileName);

            Task flushTask;
            long fileLength;
            this.TryWriteTempFile(
                tracer: null,
                source: stream,
                tempFilePath: fullPath,
                fileLength: out fileLength,
                flushTask: out flushTask,
                throwOnError: true);

            flushTask?.Wait();

            return fullPath;
        }
    

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

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

Path.GetRandomFileName的代码示例3 - GetLooseBlobStateAtPath()

    using System.IO;

        private LooseBlobState GetLooseBlobStateAtPath(string blobPath, Action writeAction, out long size)
        {
            bool corruptLooseObject = false;
            try
            {
                if (this.fileSystem.FileExists(blobPath))
                {
                    using (Stream file = this.fileSystem.OpenFileStream(blobPath, FileMode.Open, FileAccess.Read, FileShare.Read, callFlushFileBuffers: false))
                    {
                        // The DeflateStream header starts 2 bytes into the gzip header, but they are otherwise compatible
                        file.Position = 2;
                        using (DeflateStream deflate = new DeflateStream(file, CompressionMode.Decompress))
                        {
                            if (!ReadLooseObjectHeader(deflate, out size))
                            {
                                corruptLooseObject = true;
                                return LooseBlobState.Corrupt;
                            }

                            writeAction?.Invoke(deflate, size);
                            return LooseBlobState.Exists;
                        }
                    }
                }

                size = -1;
                return LooseBlobState.Missing;
            }
            catch (InvalidDataException ex)
            {
                corruptLooseObject = true;

                EventMetadata metadata = new EventMetadata();
                metadata.Add("blobPath", blobPath);
                metadata.Add("Exception", ex.ToString());
                this.tracer.RelatedWarning(metadata, nameof(this.GetLooseBlobStateAtPath) + ": Failed to stream blob (InvalidDataException)", Keywords.Telemetry);

                size = -1;
                return LooseBlobState.Corrupt;
            }
            catch (IOException ex)
            {
                EventMetadata metadata = new EventMetadata();
                metadata.Add("blobPath", blobPath);
                metadata.Add("Exception", ex.ToString());
                this.tracer.RelatedWarning(metadata, nameof(this.GetLooseBlobStateAtPath) + ": Failed to stream blob from disk", Keywords.Telemetry);

                size = -1;
                return LooseBlobState.Unknown;
            }
            finally
            {
                if (corruptLooseObject)
                {
                    string corruptBlobsFolderPath = Path.Combine(this.enlistment.EnlistmentRoot, GVFSPlatform.Instance.Constants.DotGVFSRoot, GVFSConstants.DotGVFS.CorruptObjectsName);
                    string corruptBlobPath = Path.Combine(corruptBlobsFolderPath, Path.GetRandomFileName());

                    EventMetadata metadata = new EventMetadata();
                    metadata.Add("blobPath", blobPath);
                    metadata.Add("corruptBlobPath", corruptBlobPath);
                    metadata.Add(TracingConstants.MessageKey.InfoMessage, nameof(this.GetLooseBlobStateAtPath) + ": Renaming corrupt loose object");
                    this.tracer.RelatedEvent(EventLevel.Informational, nameof(this.GetLooseBlobStateAtPath) + "_RenameCorruptObject", metadata);

                    try
                    {
                        this.fileSystem.CreateDirectory(corruptBlobsFolderPath);
                        this.fileSystem.MoveFile(blobPath, corruptBlobPath);
                    }
                    catch (Exception e)
                    {
                        metadata = new EventMetadata();
                        metadata.Add("blobPath", blobPath);
                        metadata.Add("blobBackupPath", corruptBlobPath);
                        metadata.Add("Exception", e.ToString());
                        metadata.Add(TracingConstants.MessageKey.WarningMessage, nameof(this.GetLooseBlobStateAtPath) + ": Failed to rename corrupt loose object");
                        this.tracer.RelatedEvent(EventLevel.Warning, nameof(this.GetLooseBlobStateAtPath) + "_RenameCorruptObjectFailed", metadata, Keywords.Telemetry);
                    }
                }
            }
        }
    

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

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

Path.GetRandomFileName的代码示例4 - ManualServerShutdown_NoPipeName_ShutsDownServer()

    using System.IO;

        // Skipping on MacOS because of https://github.com/dotnet/corefx/issues/33141.
        // Skipping on Linux because of https://github.com/aspnet/Razor/issues/2525.
        [ConditionalFact]
        [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
        [InitializeTestProject("SimpleMvc")]
        public async Task ManualServerShutdown_NoPipeName_ShutsDownServer()
        {
            // We are trying to test whether the correct pipe name is generated (from the location of rzc tool)
            // when we don't explicitly specify a pipe name.

            // Publish rzc tool to a temporary path. This is the location based on which the pipe name is generated.
            var solutionRoot = TestPathUtilities.GetSolutionRootDirectory("Razor");
            var toolAssemblyDirectory = Path.Combine(solutionRoot, "src", "Microsoft.AspNetCore.Razor.Tools");
            var toolAssemblyPath = Path.Combine(toolAssemblyDirectory, "Microsoft.AspNetCore.Razor.Tools.csproj");
            var projectDirectory = new TestProjectDirectory(solutionRoot, toolAssemblyDirectory, toolAssemblyPath);
            var publishDir = Path.Combine(Path.GetTempPath(), "Razor", Path.GetRandomFileName(), "RzcPublish");
            var publishResult = await MSBuildProcessManager.RunProcessAsync(projectDirectory, $"/t:Publish /p:PublishDir=\"{publishDir}\"");

            try
            {
                // Make sure publish succeeded.
                Assert.BuildPassed(publishResult);

                // Run the build using the published tool
                var toolAssembly = Path.Combine(publishDir, "rzc.dll");
                var result = await DotnetMSBuild(
                    "Build",
                    $"/p:_RazorForceBuildServer=true /p:_RazorToolAssembly={toolAssembly}",
                    suppressBuildServer: true); // We don't want to specify a pipe name

                Assert.BuildPassed(result);

                // Manually shutdown the server
                var processStartInfo = new ProcessStartInfo()
                {
                    WorkingDirectory = publishDir,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    FileName = "dotnet",
                    Arguments = $"{toolAssembly} shutdown -w"
                };

                var logFilePath = Path.Combine(publishDir, "out.log");
                processStartInfo.Environment.Add("RAZORBUILDSERVER_LOG", logFilePath);
                var shutdownResult = await MSBuildProcessManager.RunProcessCoreAsync(processStartInfo);

                Assert.Equal(0, shutdownResult.ExitCode);
                var output = await File.ReadAllTextAsync(logFilePath);
                Assert.Contains("shut down completed", output);
            }
            finally
            {
                // Finally delete the temporary publish directory
                ProjectDirectory.CleanupDirectory(publishDir);
            }
        }
    

开发者ID:aspnet,项目名称:Razor,代码行数:59,代码来源:BuildServerIntegrationTest.cs

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

Path.GetRandomFileName的代码示例5 - UploadShares()

    
        /// 
        ///     Uploads share information to the connected controller.
        /// 
        /// The unique identifier for the request.
        /// 
        [HttpPost("controller/shares/{token}")]
        [Authorize(Policy = AuthPolicy.ApiKeyOnly, Roles = AuthRole.ReadWriteOrAdministrator)]
        public async Task UploadShares(string token)
        {
            if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode))
            {
                return Forbid();
            }

            if (!Guid.TryParse(token, out var guid))
            {
                return BadRequest("Token is not a valid Guid");
            }

            if (!Request.HasFormContentType
                || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader)
                || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value))
            {
                return new UnsupportedMediaTypeResult();
            }

            var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault();
            var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault();

            if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential))
            {
                return Unauthorized();
            }

            IEnumerable shares;
            IFormFile database;

            try
            {
                shares = Request.Form["shares"].ToString().FromJson>();
                database = Request.Form.Files[0];
            }
            catch (Exception ex)
            {
                Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agentName, ex.Message);
                return BadRequest();
            }

            Log.Information("Handling share upload ({Token}) from a caller claiming to be agent {Agent}", token, agentName);

            if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential))
            {
                Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid);
                return Unauthorized();
            }

            Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName));
            var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_{agentName}_{Path.GetRandomFileName()}.db");

            try
            {
                Log.Information("Agent {Agent} authenticated for token {Token}. Beginning download of shares to {Filename}", agentName, guid, temp);

                var sw = new Stopwatch();
                sw.Start();

                using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write);
                using var inputStream = database.OpenReadStream();

                await inputStream.CopyToAsync(outputStream);

                sw.Stop();

                Log.Information("Download of shares from {Agent} ({Token}) complete ({Size} in {Duration}ms)", agentName, guid, ((double)inputStream.Length).SizeSuffix(), sw.ElapsedMilliseconds);

                await Relay.HandleShareUploadAsync(agentName, id: guid, shares, temp);

                return Ok();
            }
            catch (ShareValidationException ex)
            {
                return BadRequest(ex.Message);
            }
            finally
            {
                try
                {
                    System.IO.File.Delete(temp);
                    System.IO.File.Delete(temp + "-wal");
                    System.IO.File.Delete(temp + "-shm");
                }
                catch (Exception ex)
                {
                    Log.Debug(ex, "Failed to remove temporary share upload file: {Message}", ex.Message);
                }
            }
        }
    

开发者ID:slskd,项目名称:slskd,代码行数:98,代码来源:RelayController.cs

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

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