System.IO.Path.GetRandomFileName()

Here are the examples of the csharp api System.IO.Path.GetRandomFileName() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

567 Examples 7

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

protected override Doreplacedent OnLoad(Stream input)
        {
            Doreplacedent doc = null;
            string tempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            try
            {
                // Write the input stream to a temporary file for LibRaw to load.
                using (FileStream output = new FileStream(tempFile, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    if (input.CanSeek)
                    {
                        output.SetLength(input.Length);
                    }

                    // 81920 is the largest multiple of 4096 that is under the large object heap limit (85,000 bytes).
                    byte[] buffer = new byte[81920];

                    int bytesRead;
                    while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        output.Write(buffer, 0, bytesRead);
                    }
                }

                doc = GetRAWImageDoreplacedent(tempFile);
            }
            finally
            {
                File.Delete(tempFile);
            }

            return doc;
        }

19 View Source File : SyntaxTreeFixerEditor.cs
License : MIT License
Project Creator : 71

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;

            if (compilationConfiguration == OptimizationLevel.Debug && !runInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !runInRelease)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                int syntaxTreesLength  = compilation.SyntaxTrees.Length;
                string randomDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

                for (int i = 0; i < syntaxTreesLength; i++)
                {
                    SyntaxTree tree = compilation.SyntaxTrees[i];
                    SyntaxTree nextTree = tree;

                    string treePath = tree.FilePath;

                    SourceText source = null;

                    if (nextTree.Encoding == null)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            using (StreamWriter writer = new StreamWriter(ms, Encoding.UTF8, 4096, leaveOpen: true))
                            {
                                nextTree.GetText(cancellationToken).Write(writer, cancellationToken);
                            }

                            ms.Position = 0;

                            using (StreamReader reader = new StreamReader(ms, Encoding.UTF8, false, 4096, leaveOpen: true))
                            {
                                source = SourceText.From(reader, (int)ms.Length, Encoding.UTF8);

                                nextTree = nextTree.WithChangedText(source);
                            }
                        }
                    }

                    if (treePath != null && oldCompilation.SyntaxTrees.FirstOrDefault(x => x.FilePath == treePath) == tree)
                    {
                        // The tree already exists as a file, and is the one the user has;
                        // we don't need to change anything.

                        if (source == null)
                            // No changes applied
                            continue;

                        goto Replace;
                    }

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

                    // The tree does not exist or has been changed by an editor,
                    // we need to change its filepath, and write a new file.
                    string newPath = string.IsNullOrEmpty(treePath)
                        ? Path.Combine(randomDirectory, Path.GetRandomFileName() + ".cs")
                        : Path.Combine(randomDirectory, Path.GetFileName(treePath));

                    nextTree = nextTree.WithFilePath(newPath);

                    using (FileStream fs = File.Open(newPath, FileMode.Create, FileAccess.Write))
                    using (StreamWriter writer = new StreamWriter(fs, nextTree.Encoding, 4096))
                    {
                        if (source == null)
                            source = nextTree.GetText(cancellationToken);

                        source.Write(writer, cancellationToken);
                    }

                    Replace:
                    compilation = compilation.ReplaceSyntaxTree(tree, nextTree);
                }

                return compilation;
            }

            CompilationPipeline += EditCompilation;
        }

19 View Source File : AutomationTestBase.cs
License : MIT License
Project Creator : ABTSoftware

public string GetTemporaryDirectory()
        {
            string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            return tempDirectory;
        }

19 View Source File : UpgradeTaskBase.cs
License : MIT License
Project Creator : Accelerider

private async Task ResolveFileAsync(UpgradeInfo info)
        {
            using (var tempPath = new TempDirectory(Path.Combine(AcceleriderFolders.Temp, $"{Name}-{Path.GetRandomFileName()}")))
            {
                var zipFilePath = Path.Combine(tempPath.Path, Path.GetRandomFileName());

                // 1. Download the module
                var downloader = FileTransferService
                    .GetDownloaderBuilder()
                    .UseDefaultConfigure()
                    .From(info.Url)
                    .To(zipFilePath)
                    .Build();

                downloader.Run();

                await downloader;

                // 2. Unzip the module
                ZipFile.ExtractToDirectory(zipFilePath, tempPath.Path);

                Logger.Info($"[UNZIP] From {zipFilePath} to {tempPath.Path}");

                // 3. Move file to target path.
                var targetPath = GetInstallPath(info.Version);
                var subDirectory = Directory.GetDirectories(tempPath.Path).FirstOrDefault();
                if (tempPath.MoveTo(targetPath, subDirectory))
                {
                    Logger.Info($"[MOVE FILE] From {subDirectory} to {targetPath}");
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesDirectoriesRecursively()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a grandchild directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    Directory.CreateDirectory(Path.Combine(directory, "some child directory", "some grandchild directory"));

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DeletesDirectoryReparsePointChain()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/<guid 1> -> <guid 2>
                //   randomDir/<guid 2> -> <guid 3>
                //   randomDir/<guid 3> -> <guid 4>
                //   randomDir/<guid 4> -> <guid 5>
                //   randomDir/<guid 5> -> targetDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //
                // The purpose of this test is to verify that DirectoryNotFoundException is gracefully handled when
                // deleting a chain of reparse point directories. Since the reparse points are named in a random order,
                // the DirectoryNotFoundException case is likely to be encountered.
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir1 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir1");
                    string linkDir2 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir2");
                    string linkDir3 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir3");
                    string linkDir4 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir4");
                    string linkDir5 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir5");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir1, target: linkDir2);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir2, target: linkDir3);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir3, target: linkDir4);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir4, target: linkDir5);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir5, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir1));
                    replacedert.True(new DirectoryInfo(linkDir1).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir1, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(randomDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir1));
                    replacedert.False(Directory.Exists(targetDir));
                    replacedert.False(File.Exists(file));
                    replacedert.False(Directory.Exists(randomDir));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowNestLevel1DirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/subDir
                //   randomDir/subDir/linkDir -> ../targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string subDir = Directory.CreateDirectory(Path.Combine(randomDir, "subDir")).FullName;
                    string linkDir = Path.Combine(subDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(subDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(subDir));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void ValidateExecutePermission_DoesNotExceedFailsafe()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    Directory.CreateDirectory(directory);

                    // Act/replacedert: Call "ValidateExecutePermission". The method should not blow up.
                    IOUtil.ValidateExecutePermission(directory);
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void ValidateExecutePermission_ExceedsFailsafe()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a deep directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName(), "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20");
                try
                {
                    Directory.CreateDirectory(directory);
                    Environment.SetEnvironmentVariable("AGENT_TEST_VALIDATE_EXECUTE_PERMISSIONS_FAILSAFE", "20");

                    try
                    {
                        // Act: Call "ValidateExecutePermission". The method should throw since
                        // it exceeds the failsafe recursion depth.
                        IOUtil.ValidateExecutePermission(directory);

                        // replacedert.
                        throw new Exception("Should have thrown not supported exception.");
                    }
                    catch (NotSupportedException)
                    {
                    }
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void Delete_DeletesDirectory()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.Delete(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void Delete_DeletesFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.Delete(file, CancellationToken.None);

                    // replacedert.
                    replacedert.False(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DeletesDirectoryReparsePointsBeforeDirectories()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/linkDir -> targetDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //
                // The accuracy of this test relies on an replacedumption that IOUtil sorts the directories in
                // descending order before deleting them - either by length or by default sort order.
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir = Path.Combine(randomDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(randomDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir));
                    replacedert.False(Directory.Exists(targetDir));
                    replacedert.False(File.Exists(file));
                    replacedert.False(Directory.Exists(randomDir));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesFilesRecursively()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a grandchild file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string file = Path.Combine(directory, "some subdirectory", "some file");
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyDirectories()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a read-only subdirectory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string subdirectory = Path.Combine(directory, "some subdirectory");
                try
                {
                    var subdirectoryInfo = new DirectoryInfo(subdirectory);
                    subdirectoryInfo.Create();
                    subdirectoryInfo.Attributes = subdirectoryInfo.Attributes | FileAttributes.ReadOnly;

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    var subdirectoryInfo = new DirectoryInfo(subdirectory);
                    if (subdirectoryInfo.Exists)
                    {
                        subdirectoryInfo.Attributes = subdirectoryInfo.Attributes & ~FileAttributes.ReadOnly;
                    }

                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyRootDirectory()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a read-only directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    var directoryInfo = new DirectoryInfo(directory);
                    directoryInfo.Create();
                    directoryInfo.Attributes = directoryInfo.Attributes | FileAttributes.ReadOnly;

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    var directoryInfo = new DirectoryInfo(directory);
                    if (directoryInfo.Exists)
                    {
                        directoryInfo.Attributes = directoryInfo.Attributes & ~FileAttributes.ReadOnly;
                        directoryInfo.Delete();
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_DeletesReadOnlyFiles()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a read-only file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");
                    File.SetAttributes(file, File.GetAttributes(file) | FileAttributes.ReadOnly);

                    // Act.
                    IOUtil.DeleteDirectory(directory, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (File.Exists(file))
                    {
                        File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
                    }

                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowDirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/linkDir -> targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir = Path.Combine(randomDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(linkDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteFile_DeletesReadOnlyFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a read-only file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");
                    File.SetAttributes(file, File.GetAttributes(file) | FileAttributes.ReadOnly);

                    // Act.
                    IOUtil.DeleteFile(file);

                    // replacedert.
                    replacedert.False(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (File.Exists(file))
                    {
                        File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly);
                    }

                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowNestLevel2DirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/subDir1
                //   randomDir/subDir1/subDir2
                //   randomDir/subDir1/subDir2/linkDir -> ../../targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string subDir1 = Directory.CreateDirectory(Path.Combine(randomDir, "subDir1")).FullName;
                    string subDir2 = Directory.CreateDirectory(Path.Combine(subDir1, "subDir2")).FullName;
                    string linkDir = Path.Combine(subDir2, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(subDir1, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(subDir1));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteDirectory_IgnoresFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act: Call "DeleteDirectory" against the file. The method should not blow up and
                    // should simply ignore the file since it is not a directory.
                    IOUtil.DeleteDirectory(file, CancellationToken.None);

                    // replacedert.
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteFile_DeletesFile()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory with a file.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                string file = Path.Combine(directory, "some file");
                try
                {
                    Directory.CreateDirectory(directory);
                    File.WriteAllText(path: file, contents: "some contents");

                    // Act.
                    IOUtil.DeleteFile(file);

                    // replacedert.
                    replacedert.False(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public void DeleteFile_IgnoresDirectory()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create a directory.
                string directory = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    Directory.CreateDirectory(directory);

                    // Act: Call "DeleteFile" against a directory. The method should not blow up and
                    // should simply ignore the directory since it is not a file.
                    IOUtil.DeleteFile(directory);

                    // replacedert.
                    replacedert.True(Directory.Exists(directory));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(directory))
                    {
                        Directory.Delete(directory, recursive: true);
                    }
                }
            }
        }

19 View Source File : VerificationHelper.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static byte[] BuildreplacedemblyFromSources(string[] sourceCodes)
		{
			string replacedemblyName = Path.GetRandomFileName();
			CSharpCompilation compilation = CSharpCompilation.Create(
					replacedemblyName,
					syntaxTrees: sourceCodes.Select(code => CSharpSyntaxTree.ParseText(text: code)),
					references: _metadataReferences,
					options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

			// Emit the image of this replacedembly 
			byte[] image = null;

			using (var ms = new MemoryStream())
			{
				var emitResult = compilation.Emit(ms);

				if (!emitResult.Success)
				{
					StringBuilder diagnosticMessages = new StringBuilder(BuildFailMessage + "\r\n");
					
					IEnumerable<Diagnostic> failures = emitResult.Diagnostics.Where(diagnostic =>
															diagnostic.IsWarningAsError ||
															diagnostic.Severity == DiagnosticSeverity.Error);

					foreach (Diagnostic diagnostic in failures)
					{
						diagnosticMessages.Append(string.Format("{0}: {1} \r\n", diagnostic.Id, diagnostic.GetMessage()));
					}

					throw new ArgumentException(diagnosticMessages.ToString());
				}

				image = ms.ToArray();
			}

			return image;
		}

19 View Source File : RazorEngine.cs
License : MIT License
Project Creator : adoconnection

private MemoryStream CreateAndCompileToStream(string templateSource, RazorEngineCompilationOptions options)
        {
            templateSource = this.WriteDirectives(templateSource, options);

            RazorProjectEngine engine = RazorProjectEngine.Create(
                RazorConfiguration.Default,
                RazorProjectFileSystem.Create(@"."),
                (builder) =>
                {
                    builder.SetNamespace(options.TemplateNamespace);
                });

            string fileName = Path.GetRandomFileName();

            RazorSourceDoreplacedent doreplacedent = RazorSourceDoreplacedent.Create(templateSource, fileName);
            
            RazorCodeDoreplacedent codeDoreplacedent = engine.Process(
                doreplacedent,
                null,
                new List<RazorSourceDoreplacedent>(),
                new List<TagHelperDescriptor>());

            RazorCSharpDoreplacedent razorCSharpDoreplacedent = codeDoreplacedent.GetCSharpDoreplacedent();

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(razorCSharpDoreplacedent.GeneratedCode);

            CSharpCompilation compilation = CSharpCompilation.Create(
                fileName,
                new[]
                {
                    syntaxTree
                },
                options.Referencedreplacedemblies
                   .Select(replaced =>
                   {
#if NETSTANDARD2_0
                            return  MetadataReference.CreateFromFile(replaced.Location); 
#else
                       unsafe
                       {
                           replaced.TryGetRawMetadata(out byte* blob, out int length);
                           ModuleMetadata moduleMetadata = ModuleMetadata.CreateFromMetadata((IntPtr)blob, length);
                           replacedemblyMetadata replacedemblyMetadata = replacedemblyMetadata.Create(moduleMetadata);
                           PortableExecutableReference metadataReference = replacedemblyMetadata.GetReference();

                           return metadataReference;
                       }
#endif
                   })
                    .Concat(options.MetadataReferences)
                    .ToList(),
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            MemoryStream memoryStream = new MemoryStream();

            EmitResult emitResult = compilation.Emit(memoryStream);

            if (!emitResult.Success)
            {
                RazorEngineCompilationException exception = new RazorEngineCompilationException()
                {
                    Errors = emitResult.Diagnostics.ToList(),
                    GeneratedCode = razorCSharpDoreplacedent.GeneratedCode
                };

                throw exception;
            }

            memoryStream.Position = 0;

            return memoryStream;
        }

19 View Source File : SimpleAudioRecorderImplementation.cs
License : MIT License
Project Creator : adrianstevens

public async Task RecordAsync()
        {
            if (mediaCapture != null)
            {
                throw new InvalidOperationException("Recording already in progress");
            }

            try
            {
                var captureSettings = new MediaCaptureInitializationSettings()
                {
                    StreamingCaptureMode = StreamingCaptureMode.Audio
                };

                await InitMediaCapture(captureSettings);
            }
            catch (Exception ex)
            {
                CanRecordAudio = false;
                DeleteMediaCapture();

                if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException))
                {
                    throw ex.InnerException;
                }
                throw;
            }

            var localFolder = ApplicationData.Current.LocalFolder;
            var fileName = Path.GetRandomFileName();

            var fileOnDisk = await localFolder.CreateFileAsync(fileName);

            try
            {
                await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), fileOnDisk);
                //   await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), fileOnDisk);
            }
            catch
            {
                CanRecordAudio = false;
                DeleteMediaCapture();
                throw;
            }

            audioFilePath = fileOnDisk.Path;
        }

19 View Source File : SavePhase.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

protected override void Execute(ConfuserContext context, ProtectionParameters parameters)
        {
            var vr = context.Annotations.Get<Virtualizer>(context, Fish.VirtualizerKey);
            var merge = context.Annotations.Get<ModuleDef>(context, Fish.MergeKey);

            if(merge != null)
                return;

            var tmpDir = Path.GetTempPath();
            var outDir = Path.Combine(tmpDir, Path.GetRandomFileName());
            Directory.CreateDirectory(outDir);

            var rtPath = vr.SaveRuntime(outDir);
            if(context.Packer != null)
            {
#if DEBUG
                var protRtPath = rtPath;
#else
				var protRtPath = ProtectRT(context, rtPath);
#endif
                context.ExternalModules.Add(File.ReadAllBytes(protRtPath));
                foreach(var rule in context.Project.Rules)
                    rule.RemoveWhere(item => item.Id == Parent.Id);
            }
            else
            {
                outDir = Path.GetDirectoryName(rtPath);
                foreach(var file in Directory.GetFiles(outDir))
                {
                    var path = Path.Combine(context.OutputDirectory, Path.GetFileName(file));
                    Directory.CreateDirectory(Path.GetDirectoryName(path));
                    File.Copy(file, path, true);
                }
            }
        }

19 View Source File : SavePhase.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private string ProtectRT(ConfuserContext context, string fileName)
        {
            var outDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(outDir);

            var proj = new ConfuserProject();
            proj.Seed = context.Project.Seed;
            proj.Debug = context.Project.Debug;
            //foreach (Rule rule in context.Project.Rules) {
            //    var r = rule.Clone();
            //    r.RemoveWhere(prot => prot.Id == Parent.Id);
            //    proj.Rules.Add(r);
            //}
            proj.Rules.Add(new Rule
            {
                new SettingItem<Protection>("anti ildasm"),
                new SettingItem<Protection>("ref proxy")
                {
                    {"mode", "mild"},
                    {"typeErasure", "true"}
                },
                new SettingItem<Protection>("rename")
                {
                    {"mode", "repeating"}
                }
            });
            proj.Add(new ProjectModule
            {
                Path = fileName
            });
            proj.BaseDirectory = Path.GetDirectoryName(fileName);
            proj.OutputDirectory = outDir;
            foreach(var path in context.Project.ProbePaths)
                proj.ProbePaths.Add(path);
            proj.ProbePaths.Add(context.Project.BaseDirectory);

            StrongNameKey snKey = null;
            foreach(var module in context.Modules)
            {
                snKey = context.Annotations.Get<StrongNameKey>(module, Marker.SNKey);
                if(snKey != null)
                    break;
            }

            try
            {
                ConfuserEngine.Run(new ConfuserParameters
                {
                    Logger = new RTLogger(context.Logger),
                    Marker = new RTMarker(snKey),
                    Project = proj
                }, context.CancellationToken).Wait();
            }
            catch(AggregateException ex)
            {
                context.Logger.Error("Failed to protect Runtime.");
                throw new ConfuserException(ex);
            }

            return Path.Combine(outDir, Path.GetFileName(fileName));
        }

19 View Source File : Utils.cs
License : Apache License 2.0
Project Creator : aequabit

public static string WriteTempData(byte[] data)
        {
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            string path = null;
            try
            {
                path = Path.GetTempFileName();
            }
            catch (IOException)
            {
                path = Path.Combine(Directory.GetCurrentDirectory(), Path.GetRandomFileName());
            }
            try
            {
                File.WriteAllBytes(path, data);
            }
            catch
            {
                path = null;
            }
            return path;
        }

19 View Source File : Helpers.cs
License : GNU General Public License v3.0
Project Creator : Aetsu

public static string GetRandomString()
        {
            string path = Path.GetRandomFileName();
            path = path.Replace(".", ""); // Remove period.
            return path;
        }

19 View Source File : HyperTextViewer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

public Control GetView(File file)
        {
            var data = file.GetData();

            var ms = new MemoryStream(data);
            var hyperTextFile = new HyperTextFile();
            try
            {
                hyperTextFile.Open(ms);
            }
            finally
            {
                ms.Close();
            }

            StringWriter sw = new StringWriter();
            hyperTextFile.WriteHTML(sw);

            // Create a temporary folder
            string tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            string htmlPath = Path.Combine(tempPath, "exported.html");

            Directory.CreateDirectory(tempPath);
            System.IO.File.WriteAllText(htmlPath, sw.ToString());

            if (hyperTextFile.EmbeddedTextureFile != null)
            {
                foreach (var texture in hyperTextFile.EmbeddedTextureFile)
                {
                    string imagePath = Path.Combine(tempPath, texture.Name + ".png");

                    string directory = Path.GetDirectoryName(imagePath);
                    if (!Directory.Exists(directory))
                    {
                        Directory.CreateDirectory(directory);
                    }

                    Image image = texture.Decode();
                    image.Save(imagePath, ImageFormat.Png);
                }
            }

            WebBrowser browser = new WebBrowser();
            browser.AllowNavigation = false;
            browser.AllowWebBrowserDrop = false;
            //_browser.WebBrowserShortcutsEnabled = false;
            //_browser.IsWebBrowserContextMenuEnabled = false;

            //browser.DoreplacedentText = sw.ToString();
            browser.Navigate(htmlPath);

            browser.Disposed += delegate
                                    {
                                        Directory.Delete(tempPath, true);

                                        if (hyperTextFile.EmbeddedTextureFile != null)
                                        {
                                            hyperTextFile.EmbeddedTextureFile.Dispose();
                                        }
                                    };

            return browser;
        }

19 View Source File : Injector.cs
License : MIT License
Project Creator : Akaion

private static string CreateTemporaryDll(byte[] dllBytes)
        {
            // Ensure a directory exists on disk to store the temporary DLL

            var temporaryDirectoryInfo = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), "Bleak", "DLL"));

            // Clear the directory

            foreach (var file in temporaryDirectoryInfo.EnumerateFiles())
            {
                try
                {
                    file.Delete();
                }

                catch (Exception)
                {
                    // The file is currently open and cannot be safely deleted
                }
            }

            // Create a temporary DLL with a randomised name

            var temporaryDllPath = Path.Combine(temporaryDirectoryInfo.FullName, Path.GetRandomFileName() + ".dll");

            try
            {
                File.WriteAllBytes(temporaryDllPath, dllBytes);
            }

            catch (IOException)
            {
                // A DLL already exists with the specified name, is loaded in a process and cannot be safely overwritten
            }

            return temporaryDllPath;
        }

19 View Source File : RandomUtils.cs
License : MIT License
Project Creator : AlexanderFroemmgen

public static string GetRandomIdentifier(int length)
        {
            return Path.GetRandomFileName().Replace(".", "").Substring(0, length);
        }

19 View Source File : FileSystemResultsWriterTests.cs
License : Apache License 2.0
Project Creator : allure-framework

[Test, Description("Cleanup test")]
        public void ShouldCleanupTempResultsFolder()
        {
            var resultsDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var json = $"{{\"allure\":{{\"directory\": {JsonConvert.ToString(resultsDirectory)}}}}}";
            var config = AllureConfiguration.ReadFromJObject(JObject.Parse(json));
            Directory.CreateDirectory(resultsDirectory);
            File.WriteAllText(Path.Combine(resultsDirectory, Path.GetRandomFileName()), "");

            new FileSystemResultsWriter(config).CleanUp();
            replacedert.IsEmpty(Directory.GetFiles(resultsDirectory));
        }

19 View Source File : InstantiationTests.cs
License : Apache License 2.0
Project Creator : allure-framework

[Test]
        public void ShouldReadConfigFromEnvironmentVariable()
        {
            var configuration = @"{""allure"":{""directory"": ""env""}}";

            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            var configFile = Path.Combine(tempDirectory, AllureConstants.CONFIG_FILENAME);
            File.WriteAllText(configFile, configuration);
            Environment.SetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE, configFile);

            replacedert.AreEqual("env", new AllureLifecycle().AllureConfiguration.Directory);
        }

19 View Source File : InstantiationTests.cs
License : Apache License 2.0
Project Creator : allure-framework

[Test]
        public void ShouldThrowIfEnvVariableConfigNotFound()
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            Environment.SetEnvironmentVariable(AllureConstants.ALLURE_CONFIG_ENV_VARIABLE,
                Path.Combine(tempDirectory, AllureConstants.CONFIG_FILENAME));

            replacedert.Throws<FileNotFoundException>(() => { new AllureLifecycle(); });
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : AmazingDM

public static void Main(string[] args)
        {
            var result = false;

            try
            {
                #region Check Arguments

                if (CurrentProcess.MainModule == null)
                {
                    Console.WriteLine("Current Process MainModule is null");
                    return;
                }

                if (args.Length != 3)
                {
                    Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
                    return;
                }

                // arg0 port
                if (!int.TryParse(args[0], out var port))
                {
                    Console.WriteLine("arg0 Port Parse failed");
                    return;
                }

                var updateExtracted = true;
                // arg1 update File/Directory
                var updatePath = Path.GetFullPath(args[1]);
                if (File.Exists(updatePath))
                {
                    updateExtracted = false;
                }
                else if (!Directory.Exists(updatePath))
                {
                    Console.WriteLine("arg1 update file/directory Not found");
                    return;
                }

                // arg2 target Directory
                string targetPath;
                if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
                {
                    Console.Write("arg2 Netch Directory doesn't seems right");
                    return;
                }

                #region if under target Directory,then rerun in temp directory

                if (UpdaterDirectory.StartsWith(targetPath))
                {
                    // Updater 在目标目录下
                    // 将程序复制到临时目录,传递参数
                    var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                    var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
                    Directory.CreateDirectory(tempPath);
                    File.Copy(UpdaterFullName, newUpdaterPath);
                    Process.Start(new ProcessStartInfo
                    {
                        FileName = newUpdaterPath,
                        Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
                        WorkingDirectory = tempPath,
                        UseShellExecute = false
                    });
                    result = true;
                    return;
                }

                #endregion

                #endregion

                /*Console.WriteLine("Waiting Attach");
                while (!Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }*/

                #region Send Netch Exit command

                Process[] _;
                if ((_ = Process.GetProcessesByName("Netch")).Any())
                {
                    Console.WriteLine("Found Netch process, Send exit command");
                    try
                    {
                        var udpClient = new UdpClient("127.0.0.1", port);
                        var sendBytes = Encoding.ASCII.GetBytes("Exit");
                        udpClient.Send(sendBytes, sendBytes.Length);
                    }
                    catch
                    {
                        Console.WriteLine("Send command failed");
                        return;
                    }

                    foreach (var proc in _)
                    {
                        try
                        {
                            proc.WaitForExit();
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                    }
                }

                #endregion

                var counter = 0;
                while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
                {
                    // wait 5 sec
                    if (counter > 25)
                    {
                        Console.WriteLine("Waiting Netch exit timeout");
                        return;
                    }

                    Thread.Sleep(200);
                    counter++;
                }

                #region Update

                string extractPath = null;
                if (!updateExtracted)
                {
                    extractPath = Path.Combine(UpdaterDirectory, "extract");
                    Extract(updatePath, extractPath, true);

                    var netchExeFileInfo = FindFile("Netch.exe", extractPath);

                    if (netchExeFileInfo == null)
                    {
                        throw new Exception("Netch.exe not found in archive!");
                    }

                    updatePath = netchExeFileInfo.Directory.FullName;
                }

                MoveDirectory(updatePath, targetPath, true);

                try
                {
                    if (extractPath != null)
                        Directory.Delete(extractPath, true);
                }
                catch
                {
                    // ignored
                }

                #endregion

                #region Finished Update,Start Netch

                Console.WriteLine("Start Netch");
                Process.Start(new ProcessStartInfo
                {
                    FileName = Path.Combine(targetPath, "Netch.exe"),
                    UseShellExecute = true,
                });

                #endregion

                result = true;
            }
            catch (Exception e)
            {
                if (e is InvalidDataException)
                    Console.WriteLine("Archive file Broken");
                Console.WriteLine(e.ToString());
            }
            finally
            {
                if (!result)
                {
                    Console.WriteLine("Press any key to exit...");
                    Console.Read();
                }
            }
        }

19 View Source File : SelfUpdateProgressPage.cs
License : GNU General Public License v3.0
Project Creator : Amebis

public override void OnActivate()
        {
            base.OnActivate();

            // Setup self-update.
            var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
            selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
            {
                selfUpdate.ReportProgress(0);
                var random = new Random();
                var tempFolder = Path.GetTempPath();
                var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
                Directory.CreateDirectory(workingFolder);
                try
                {
                    string installerFilename = null;
                    FileStream installerFile = null;

                    // Download installer.
                    while (DownloadUris.Count > 0)
                    {
                        Window.Abort.Token.ThrowIfCancellationRequested();
                        var uriIndex = random.Next(DownloadUris.Count);
                        try
                        {
                            var binaryUri = DownloadUris[uriIndex];
                            Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
                            var request = WebRequest.Create(binaryUri);
                            request.Proxy = null;
                            using (var response = request.GetResponse())
                            {
                                // 1. Get installer filename from Content-Disposition header.
                                // 2. Get installer filename from the last segment of URI path.
                                // 3. Fallback to a predefined installer filename.
                                try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
                                catch
                                {
                                    try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
                                    catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
                                }

                                // Save response data to file.
                                installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                                try
                                {
                                    using (var stream = response.GetResponseStream())
                                    {
                                        installerFile.Seek(0, SeekOrigin.Begin);
                                        var hash = new eduEd25519.SHA256();
                                        var buffer = new byte[1048576];
                                        long offset = 0, total = response.ContentLength;

                                        for (; ; )
                                        {
                                            // Wait for the data to arrive.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            var bufferLength = stream.Read(buffer, 0, buffer.Length);
                                            if (bufferLength == 0)
                                                break;
                                            //Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.

                                            // Append it to the file and hash it.
                                            Window.Abort.Token.ThrowIfCancellationRequested();
                                            installerFile.Write(buffer, 0, bufferLength);
                                            hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);

                                            // Report progress.
                                            offset += bufferLength;
                                            selfUpdate.ReportProgress((int)(offset * 100 / total));
                                        }

                                        hash.TransformFinalBlock(buffer, 0, 0);
                                        if (!hash.Hash.SequenceEqual(Hash))
                                            throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));

                                        installerFile.SetLength(installerFile.Position);
                                        break;
                                    }
                                }
                                catch
                                {
                                    // Close installer file.
                                    installerFile.Close();
                                    installerFile = null;

                                    // Delete installer file. If possible.
                                    Trace.TraceInformation("Deleting file {0}...", installerFilename);
                                    try { File.Delete(installerFilename); }
                                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
                                    installerFilename = null;

                                    throw;
                                }
                            }
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex)
                        {
                            Trace.TraceWarning("Error: {0}", ex.ToString());
                            DownloadUris.RemoveAt(uriIndex);
                        }
                    }

                    if (installerFilename == null || installerFile == null)
                    {
                        // The installer file is not ready.
                        throw new InstallerFileUnavailableException();
                    }

                    try
                    {
                        var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
                        var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
                        try
                        {
                            // Prepare WSF file.
                            var writer = new XmlTextWriter(updaterFile, null);
                            writer.WriteStartDoreplacedent();
                            writer.WriteStartElement("package");
                            writer.WriteStartElement("job");

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "WScript.Shell");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("reference");
                            writer.WriteAttributeString("object", "Scripting.FileSystemObject");
                            writer.WriteEndElement(); // reference

                            writer.WriteStartElement("script");
                            writer.WriteAttributeString("language", "JScript");
                            var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
                            var argv = Environment.GetCommandLineArgs();
                            var arguments = new StringBuilder();
                            for (long i = 1, n = argv.LongLength; i < n; i++)
                            {
                                if (i > 1) arguments.Append(" ");
                                arguments.Append("\"");
                                arguments.Append(argv[i].Replace("\"", "\"\""));
                                arguments.Append("\"");
                            }
                            var script = new StringBuilder();
                            script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
                            script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
                            script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
                            script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
                            writer.WriteCData(script.ToString());
                            writer.WriteEndElement(); // script

                            writer.WriteEndElement(); // job
                            writer.WriteEndElement(); // package
                            writer.WriteEndDoreplacedent();
                            writer.Flush();

                            // Prepare WSF launch parameters.
                            Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
                            var process = new Process();
                            process.StartInfo.FileName = "wscript.exe";
                            process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
                            process.StartInfo.WorkingDirectory = workingFolder;

                            // Close WSF and installer files as late as possible to narrow the attack window.
                            // If Windows supported executing files that are locked for writing, we could leave those files open.
                            updaterFile.Close();
                            installerFile.Close();
                            process.Start();
                        }
                        catch
                        {
                            // Close WSF file.
                            updaterFile.Close();

                            // Delete WSF file. If possible.
                            Trace.TraceInformation("Deleting file {0}...", updaterFilename);
                            try { File.Delete(updaterFilename); }
                            catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }

                            throw;
                        }
                    }
                    catch
                    {
                        // Close installer file.
                        installerFile.Close();

                        // Delete installer file. If possible.
                        Trace.TraceInformation("Deleting file {0}...", installerFilename);
                        try { File.Delete(installerFilename); }
                        catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }

                        throw;
                    }
                }
                catch
                {
                    // Delete working folder. If possible.
                    try { Directory.Delete(workingFolder); }
                    catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }

                    throw;
                }
            };

            // Self-update progress.
            selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
            {
                Progress.Value = e.ProgressPercentage;
            };

            // Self-update complereplacedion.
            selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
            {
                if (e.Error == null)
                {
                    // Self-updating successfuly launched. Quit to release open files.
                    Wizard.OnQuitApplication(this);
                }
                else
                    Wizard.Error = e.Error;

                // Self-dispose.
                (sender as BackgroundWorker)?.Dispose();
            };

            selfUpdate.RunWorkerAsync();
        }

19 View Source File : FileIconMapperTest.cs
License : Apache License 2.0
Project Creator : AmpScm

[Test]
        public void TestExistingFileType()
        {
            var statusCache = new Mock<ISvnStatusCache>();

            string tempFile = Path.GetTempFileName();
            string exeTempFile = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".exe");
            using (File.CreateText(exeTempFile))
            { }

            try
            {
                var item = new SvnItem(statusCache.Object, tempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("TMP File"));

                item = new SvnItem(statusCache.Object, exeTempFile, NoSccStatus.Unknown, SharpSvn.SvnNodeKind.File);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("Application"));

                item = new SvnItem(statusCache.Object, "C:\\", NoSccStatus.Unknown, SharpSvn.SvnNodeKind.Directory);
                replacedert.That(mapper.GetFileType(item), Is.EqualTo("Local Disk"));
            }
            finally
            {
                File.Delete(tempFile);
                File.Delete(exeTempFile);
            }
        }

19 View Source File : FileProcessor.cs
License : MIT License
Project Creator : Analogy-LogViewer

private string UnzipFilesIntoTempFolder(string zipPath, IreplacedogyOfflineDataProvider fileDataProvider)
        {
            string extractPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(extractPath);
            if (zipPath.EndsWith("zip", StringComparison.InvariantCultureIgnoreCase))
            {
                UnzipZipFileIntoTempFolder(zipPath, extractPath, fileDataProvider);
            }
            else if (zipPath.EndsWith("gz", StringComparison.InvariantCultureIgnoreCase))
            {
                UnzipGzFileIntoTempFolder(zipPath, extractPath);
            }
            else
            {
                replacedogyLogger.Instance.LogError(nameof(UnzipFilesIntoTempFolder), $"Unsupported file: {zipPath}.");
                return string.Empty;
            }

            return extractPath;
        }

19 View Source File : CardsProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public async Task Navigate(CardsView cardsView, params ProcessorItem[] items)
        {
            var animations = new List<Task>();
            ProcessorItem? endItem = null;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {

                    view.IsVisible = true;
                    animations.Add(new AnimationWrapper(v => {
                        if (double.IsNaN(v))
                        {
                            return;
                        }
                        view.Scale = v;
                    }, view.Scale, 1).Commit(view, Path.GetRandomFileName(), 16, AnimationLength, AnimationEasing));
                    continue;
                }

                animations.Add(new AnimationWrapper(v => HandleAutoAnimatingPosChanged(view, cardsView, v, item.Direction), 0, cardsView.RealMoveDistance)
                    .Commit(view, Path.GetRandomFileName(), 16, AnimationLength, AnimationEasing));
                endItem = item;
            }
            await Task.WhenAll(animations);
            if (endItem.HasValue)
            {
                await Proceed(cardsView, endItem.GetValueOrDefault());
            }
        }

19 View Source File : CardsProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public async Task Proceed(CardsView cardsView, params ProcessorItem[] items)
        {
            var animation = new AnimationWrapper();
            Action onFinish = null;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();

                if (item.IsFront)
                {
                    if (view != null)
                    {
                        view.Scale = 1;
                    }
                    continue;
                }

                if (view != null)
                {
                    animation.Add(0, 1, new AnimationWrapper(v => view.Opacity = v, view.Opacity, 0));
                    onFinish = () => view.IsVisible = false;
                }
            }
            await animation.Commit(cardsView, Path.GetRandomFileName(), 16, AnimationLength, AnimationEasing);
            onFinish?.Invoke();
        }

19 View Source File : CardsProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public async Task Reset(CardsView cardsView, params ProcessorItem[] items)
        {
            var animation = new AnimationWrapper();
            var animLength = AnimationLength;
            Action onFinish = null;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();

                if (item.IsFront)
                {
                    onFinish = () => ResetInitialState(view, cardsView, true);
                    animLength = (uint)(AnimationLength * Min(Abs(view.TranslationX / cardsView.RealMoveDistance), 1.0));

                    if (animLength == 0)
                    {
                        continue;
                    }

                    animation.Add(0, 1, new AnimationWrapper {
                        { 0, 1, new AnimationWrapper (v => SetTranslationX(view, v, cardsView, true), view.TranslationX, 0) },
                        { 0, 1, new AnimationWrapper (v => view.TranslationY = v, view.TranslationY, 0) },
                        { 0, 1, new AnimationWrapper (v => view.Rotation = v, view.Rotation, 0) }
                    });
                    continue;
                }
                if (view == null || view == cardsView.CurrentView)
                {
                    continue;
                }
                animation.Add(0, 1, new AnimationWrapper(v => {
                    if(double.IsNaN(v))
                    {
                        return;
                    }
                    view.Scale = v;
                }, view.Scale, BackViewInitialScale));
            }
            await animation.Commit(cardsView, Path.GetRandomFileName(), 16, animLength, AnimationEasing);
            onFinish?.Invoke();
        }

19 View Source File : CoverFlowProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public override Task Navigate(CardsView cardsView, params ProcessorItem[] items)
        {
            var step = GetStep(cardsView);
            var animation = new AnimationWrapper();
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                var otherViews = item.Views.Union(item.InactiveViews ?? Enumerable.Empty<View>()).Except(Enumerable.Repeat(view, 1));
                animation.Add(0, 1, new AnimationWrapper(v => ProceedPositionChanged(v, view, otherViews, cardsView), 0, -Sign((int)item.Direction) * step));

            }
            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, AnimationLength, AnimationEasing);
        }

19 View Source File : CoverFlowProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public override Task Proceed(CardsView cardsView, params ProcessorItem[] items)
        {
            var step = GetStep(cardsView);
            var animation = new AnimationWrapper();
            var animLength = AnimationLength;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {
                    var animTimePercent = 1 - (step - Abs(GetTranslationX(view, cardsView))) / step;
                    animLength = Max((uint)(AnimationLength * animTimePercent), 1);
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                var otherViews = item.Views.Union(item.InactiveViews ?? Enumerable.Empty<View>()).Except(Enumerable.Repeat(view, 1));
                animation.Add(0, 1, new AnimationWrapper(v => ProceedPositionChanged(v, view, otherViews, cardsView), GetTranslationX(view, cardsView), -Sign((int)item.Direction) * step));
            }
            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, animLength, AnimationEasing);
        }

19 View Source File : CoverFlowProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public override Task Reset(CardsView cardsView, params ProcessorItem[] items)
        {
            var step = GetStep(cardsView);
            var animation = new AnimationWrapper();
            var animLength = AnimationLength;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {
                    var animTimePercent = 1 - (step - Abs(GetTranslationX(view, cardsView))) / step;
                    animLength = Max((uint)(AnimationLength * animTimePercent) * 3 / 2, 1);
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                if (view == cardsView.CurrentView)
                {
                    continue;
                }
                var otherViews = item.Views.Union(item.InactiveViews ?? Enumerable.Empty<View>()).Except(Enumerable.Repeat(view, 1));
                animation.Add(0, 1, new AnimationWrapper(v => ProceedPositionChanged(v, view, otherViews, cardsView), GetTranslationX(view, cardsView), Sign((int)item.Direction) * step));
            }
            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, animLength, AnimationEasing);
        }

19 View Source File : CarouselProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public virtual Task Proceed(CardsView cardsView, params ProcessorItem[] items)
        {
            var animation = new AnimationWrapper();
            var animLength = AnimationLength;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {
                    var animTimePercent = 1 - (cardsView.GetSize() - Abs(GetTranslationX(view, cardsView))) / cardsView.GetSize();
                    animLength = Max((uint)(AnimationLength * animTimePercent), 1);
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, false), GetTranslationX(view, cardsView), -Sign((int)item.Direction) * cardsView.GetSize()));
            }

            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, animLength, AnimationEasing);
        }

19 View Source File : CarouselProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public virtual Task Reset(CardsView cardsView, params ProcessorItem[] items)
        {
            var animation = new AnimationWrapper();
            var animLength = AnimationLength;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }

                if (item.IsFront)
                {
                    var animTimePercent = 1 - (cardsView.GetSize() - Abs(GetTranslationX(view, cardsView))) / cardsView.GetSize();
                    animLength = Max((uint)(AnimationLength * animTimePercent) * 3 / 2, 1);
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                if (view == cardsView.CurrentView)
                {
                    continue;
                }
                animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, false), GetTranslationX(view, cardsView), Sign((int)item.Direction) * cardsView.GetSize()));
            }

            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, animLength, AnimationEasing);
        }

19 View Source File : HotCompiler.cs
License : MIT License
Project Creator : AndreiMisiukevich

public Type Compile(string code, string clreplacedName)
            {
                if (IsSupported == false)
                {
                    return null;
                }
                try
                {
                    var syntaxTree = CSharpSyntaxTree.ParseText(code);
                    var replacedemblyName = $"HotReload.HotCompile.{Path.GetRandomFileName().Replace(".", string.Empty) }";

                    var compilation = CSharpCompilation.Create(
                        replacedemblyName,
                        new[] { syntaxTree },
                        _references,
                        new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

                    using (var stream = new MemoryStream())
                    {
                        var compilationResult = compilation.Emit(stream);

                        if (!compilationResult.Success)
                        {
                            var failures = compilationResult.Diagnostics
                                .Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

                            foreach (var failure in failures)
                            {
                                Console.Error.WriteLine("\t{0}: {1}", failure.Id, failure.GetMessage());
                            }

                            return null;
                        }
                        stream.Seek(0, SeekOrigin.Begin);

                        var bytes = stream.ToArray();
                        var replacedembly = replacedembly.Load(bytes);
                        var type = replacedembly.GetType(clreplacedName);
                        return type;
                    }
                }
                catch
                {
                    Console.WriteLine($"HOTRELOADER ERROR: Couldn't compile {code}");
                    return null;
                }
            }

19 View Source File : CarouselProcessor.cs
License : MIT License
Project Creator : AndreiMisiukevich

public virtual Task Navigate(CardsView cardsView, params ProcessorItem[] items)
        {
            var animation = new AnimationWrapper();
            var lenght = AnimationLength;
            foreach (var item in items)
            {
                var view = item.Views.FirstOrDefault();
                if (view == null)
                {
                    continue;
                }
                view.IsVisible = true;
                if (item.IsFront)
                {
                    animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, true), GetTranslationX(view, cardsView), 0));
                    continue;
                }

                var destinationPos = item.Direction == AnimationDirection.Prev
                    ? cardsView.GetSize()
                    : -cardsView.GetSize();

                animation.Add(0, 1, new AnimationWrapper(v => SetTranslationX(view, v, cardsView, false), 0, destinationPos));
            }
            return animation.Commit(cardsView, Path.GetRandomFileName(), 16, AnimationLength, AnimationEasing);
        }

19 View Source File : ChatRoomPage.xaml.cs
License : MIT License
Project Creator : AndreiMisiukevich

private void OnMessage(object sender, EventArgs e)
        {
            CrossOpenTok.Current.SendMessageAsync($"Path.GetRandomFileName: {Path.GetRandomFileName()}");
        }

See More Examples