GetRandomFileName() public static method

public static GetRandomFileName ( ) : string
return string
        void NotifyWebAppisHosted(string webAppVersionString)
        {
            WebAppVersion = webAppVersionString;
            string jsResults;

            using (var context = new AutoJSContext(_browser.Window.JSContext))
                using (new JSAutoCompartment(context, (nsISupports)_browser.Window.DomWindow))
                {
                    context.EvaluateScript("hostedAppSetup();", out jsResults);
                }

            //This loads the last saved program. We know at this point that everything should be working in Blockly.
            if (!string.IsNullOrWhiteSpace(Settings.Default.SavedProgram))
            {
                string tempPath = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());
                Directory.CreateDirectory(tempPath);
                string tempLoadingFile = IOPath.Combine(tempPath, "temp_blocks.xml");
                using (var file = File.OpenWrite(tempLoadingFile))
                    using (var sw = new StreamWriter(file))
                    {
                        sw.Write(Settings.Default.SavedProgram);
                    }
                _tempPathsCreated.Add(tempPath);
                string fileUri = "file://" + new FileInfo(tempLoadingFile).FullName;

                using (var context = new AutoJSContext(_browser.Window.JSContext))
                    using (var compartment = new JSAutoCompartment(context, (nsISupports)_browser.Window.DomWindow))
                    {
                        string output;
                        context.EvaluateScript("load_by_url('" + fileUri.Replace("\\", "/") + "');", out output);
                    }
            }
        }
Ejemplo n.º 2
0
        public void ShouldGetFileInfoWithMultipleHardLinks()
        {
            var path = IOPath.GetTempPath();

            path = IOPath.Combine(path, IOPath.GetRandomFileName());

            var file = IOFile.Create(path);

            file.Close();

            var linkPath = IOPath.GetTempPath();

            linkPath = IOPath.Combine(linkPath, IOPath.GetRandomFileName());

            CFile.CreateHardLink(linkPath, path);

            try
            {
                var fileInfo = new CFileInfo(path);
                Assert.That(fileInfo.LinkCount, Is.EqualTo(2), "LinkCount");
            }
            finally
            {
                IOFile.Delete(path);
                IOFile.Delete(linkPath);
            }
        }
Ejemplo n.º 3
0
        public void ShouldCreateJunctionPoint()
        {
            var path = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Path.GetRandomFileName());

            Directory.CreateDirectory(path);
            var file = Path.Combine(path, "file.txt");

            using (File.Create(file))
            {
            }

            var junctionPath = string.Format("{0}+junction", path);

            JunctionPoint.Create(junctionPath, path, true);
            var junctionFiles = Directory.GetFiles(junctionPath);

            Assert.That(junctionFiles.Length, Is.EqualTo(1));
            Assert.That(junctionFiles[0], Is.EqualTo(Path.Combine(junctionPath, "file.txt")));


            JunctionPoint.Delete(junctionPath);

            Assert.That(Directory.Exists(junctionPath), Is.False);
            Assert.That(File.Exists(file), Is.True);
        }
        /// <summary>
        /// Gets the set of search paths by running the interpreter.
        /// </summary>
        /// <param name="interpreter">Path to the interpreter.</param>
        /// <returns>A list of search paths for the interpreter.</returns>
        /// <remarks>Added in 2.2, moved in 3.3</remarks>
        public static async Task <List <PythonLibraryPath> > GetUncachedDatabaseSearchPathsAsync(string interpreter)
        {
            // sys.path will include the working directory, so we make an empty
            // path that we can filter out later
            var tempWorkingDir = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());

            Directory.CreateDirectory(tempWorkingDir);
            if (!InstallPath.TryGetFile("get_search_paths.py", out var srcGetSearchPaths))
            {
                return(new List <PythonLibraryPath>());
            }
            var getSearchPaths = IOPath.Combine(tempWorkingDir, PathUtils.GetFileName(srcGetSearchPaths));

            File.Copy(srcGetSearchPaths, getSearchPaths);

            var lines      = new List <string>();
            var errorLines = new List <string> {
                "Cannot obtain list of paths"
            };

            try {
                using (var proc = new ProcessHelper(interpreter, new[] { "-S", "-E", getSearchPaths }, tempWorkingDir)) {
                    proc.OnOutputLine = lines.Add;
                    proc.OnErrorLine  = errorLines.Add;

                    proc.Start();
                    using (var cts = new CancellationTokenSource(30000)) {
                        int exitCode;
                        try {
                            exitCode = await proc.WaitAsync(cts.Token).ConfigureAwait(false);
                        } catch (OperationCanceledException) {
                            proc.Kill();
                            exitCode = -1;
                        }
                        if (exitCode != 0)
                        {
                            throw new InvalidOperationException(string.Join(Environment.NewLine, errorLines));
                        }
                    }
                }
            } finally {
                PathUtils.DeleteDirectory(tempWorkingDir);
            }

            return(lines.Select(s => {
                if (s.StartsWithOrdinal(tempWorkingDir, ignoreCase: true))
                {
                    return null;
                }
                try {
                    return Parse(s);
                } catch (ArgumentException) {
                    Debug.Fail("Invalid search path: " + (s ?? "<null>"));
                    return null;
                } catch (FormatException) {
                    Debug.Fail("Invalid format for search path: " + s);
                    return null;
                }
            }).Where(p => p != null).ToList());
        }
Ejemplo n.º 5
0
        public static string GetTemporaryDirectory()
        {
            var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            Directory.CreateDirectory(tempDirectory);
            return(tempDirectory);
        }
Ejemplo n.º 6
0
 public InstallationInfo(Install install, Boolean differentLanguage)
 {
     Install           = install;
     DifferentLanguage = differentLanguage;
     ExtractDirectory  = P.Combine(P.GetTempPath(), P.GetRandomFileName());
     // GetRandomFileName doesn't create anything unlike GetTempFileName
 }
Ejemplo n.º 7
0
 public TestDirectory()
 {
     _path = IOPath.Combine(
         AppDomain.CurrentDomain.BaseDirectory,
         IOPath.GetRandomFileName());
     Directory.CreateDirectory(_path);
 }
Ejemplo n.º 8
0
        public string GetPathForNewVideo()
        {
            var tempFile      = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var tempVideoFile = Path.ChangeExtension(tempFile, CommonConstants.VIDEO_EXTENSION);

            return(Path.Combine(LOCAL_VIDEO_LOCATION, tempVideoFile));
        }
Ejemplo n.º 9
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            cat.EnableValidation = true;

            if (string.IsNullOrEmpty(cat.Error))
            {
                if (!string.IsNullOrEmpty(file_selected))
                {
                    string ext = Path.GetExtension(file_selected);

                    string fileName = Path.GetRandomFileName() + ext;

                    string fileSavePath = Path.Combine(Directory.GetCurrentDirectory(),
                                                       "images", fileName);

                    var bmp = ResizeImage.ResizeOrigImg(
                        new Bitmap(System.Drawing.Image.FromFile(file_selected)), 75, 75);

                    bmp.Save(fileSavePath, ImageFormat.Jpeg);

                    file_name = fileSavePath;
                }
                var cat_info =
                    new AppCat
                {
                    Name        = tbname.Text,
                    Birth       = (DateTime)bdcat.SelectedDate,
                    Description = tbdesc.Text,
                    Gender      = cbitem.Text.ToString(),
                    Image       = file_name
                };
                cat_info.AppCatPrices = new List <AppCatPrice>
                {
                    new AppCatPrice
                    {
                        CatId      = cat_info.Id,
                        DateCreate = DateTime.Now,
                        Price      = decimal.Parse(tbprice.Text)
                    }
                };

                _cats.Add(new CatVM
                {
                    Id          = cat_info.Id.ToString(),
                    Name        = cat_info.Name,
                    Birthday    = cat_info.Birth,
                    Description = cat_info.Description,
                    Image       = cat_info.Image
                });

                _context.Add(cat_info);
                _context.SaveChanges();

                Close();
            }
            else
            {
                MessageBox.Show(cat.Error);
            }
        }
        void _browser_CreateWindow(object sender, GeckoCreateWindowEventArgs e)
        {
            //Console.WriteLine(e);
            if (!string.IsNullOrWhiteSpace(e.Uri))
            {
                string browserUrl  = _browser.Url.GetLeftPart(UriPartial.Path);
                string browserRoot = browserUrl.Substring(0, browserUrl.LastIndexOf('/'));
                if (e.Uri.StartsWith(browserRoot) && false)
                {
                    //then we're opening a local file
                }
                else
                {
                    var uri = e.Uri == "https://www.paypal.com/cgi-bin/webscr" ?
                              "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=DXBL3RF9PNXJU" : //donate button was clicked. then we change the URL from a form submit
                              e.Uri;

                    //Create a temporary file to open in the browser. This is hackish, but gives us a ton more control
                    //of how the page loads, in a platform and browser-agnostic way. Without this, we'd have a hard time
                    //opening to anchors.
                    string template =
                        @"<html>
    <head>
        <meta http-equiv='refresh' content='0;url={0}' />
    </head>
</html>
";
                    string tempFileContents = string.Format(template, uri);
                    string tempPath         = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());
                    string browseTempFile   = IOPath.Combine(tempPath, "temp.html");

                    Directory.CreateDirectory(tempPath);

                    using (var f = File.OpenWrite(browseTempFile))
                        using (var sw = new StreamWriter(f))
                        {
                            sw.Write(tempFileContents);
                            _tempPathsCreated.Add(tempPath);
                        }

                    ProcessStartInfo info = new ProcessStartInfo()
                    {
                        UseShellExecute = true,
                        FileName        = "file:///" + new FileInfo(browseTempFile).FullName
                    };

                    var proc = new Process()
                    {
                        StartInfo = info
                    };

                    proc.Start();
                }

                e.Cancel = true;
                Console.WriteLine(e.Uri);
            }
        }
Ejemplo n.º 11
0
 public void ShouldIgnoreFileThatDoesNotExist()
 {
     Assert.Throws <FileNotFoundException>(() =>
     {
         var path = IOPath.GetTempPath();
         path     = IOPath.Combine(path, IOPath.GetRandomFileName());
         new CFileInfo(path);
     });
 }
        public void ShouldGetTargetPathForJunction()
        {
            var path = IOPath.Combine(Environment.GetEnvironmentVariable("TEMP"), IOPath.GetRandomFileName());

            Directory.CreateDirectory(path);
            var junctionPath = string.Format("{0}+junction", path);

            JunctionPoint.Create(junctionPath, path, true);
            Assert.That(ReparsePoint.GetTarget(junctionPath), Is.EqualTo(path));
        }
Ejemplo n.º 13
0
 static EnvDTE.Project CreateTemporaryProject(VisualStudioApp app, [CallerMemberName] string projectName = null) {
     var project = app.CreateProject(
         PythonVisualStudioApp.TemplateLanguageName,
         PythonVisualStudioApp.PythonApplicationTemplate,
         TestData.GetTempPath(),
         projectName ?? Path.GetFileNameWithoutExtension(Path.GetRandomFileName())
     );
     Assert.IsNotNull(project, "Project was not created");
     return project;
 }
Ejemplo n.º 14
0
        // Збереження нового кота
        private void SaveCat_Click(object sender, RoutedEventArgs e)
        {
            newCat.EnableValidation = true;
            if (string.IsNullOrEmpty(newCat.Error))
            {
                MessageBox.Show("Додавання успішне");
                var extension = Path.GetExtension(FileName);
                var imageName = Path.GetRandomFileName() + extension;
                var dir       = Directory.GetCurrentDirectory();
                var saveDir   = Path.Combine(dir, "images");
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }
                var fileSave = Path.Combine(saveDir, imageName);
                File.Copy(FileName, fileSave);

                var cat =
                    new AppCat
                {
                    Name     = tbName.Text,
                    Gender   = _gender,
                    Birthday = (DateTime)dpDate.SelectedDate,
                    Details  = tbDetails.Text,
                    Image    = fileSave
                };
                cat.AppCatPrices = new List <AppCatPrice>
                {
                    new AppCatPrice
                    {
                        CatId      = cat.Id,
                        DateCreate = DateTime.Now,
                        Price      = decimal.Parse(tbPrice.Text)
                    }
                };
                _context.Add(cat);
                _context.SaveChanges();

                _cats.Add(new CatVM
                {
                    Id       = cat.Id,
                    Name     = cat.Name,
                    Birthday = cat.Birthday,
                    Details  = cat.Details,
                    ImageUrl = cat.Image
                });

                this.Close();
            }
            else
            {
                MessageBox.Show(newCat.Error);
            }
        }
Ejemplo n.º 15
0
        private void btnSaveChangs_Click(object sender, RoutedEventArgs e)
        {
            us.EnableValidation = true;
            var usChangNew = _context.Users.SingleOrDefault(p => p.Id == MainWindow.chang_User);

            if (!string.IsNullOrEmpty(this.tbName.Text))
            {
                usChangNew.Name = tbName.Text;
            }
            if (!string.IsNullOrEmpty(this.tbDetails.Text))
            {
                usChangNew.Details = tbDetails.Text;
            }

            if (!string.IsNullOrEmpty(this.tbPrice.Text))
            {
                this._context.AppTranzactionPrices.Add(new AppTranzactionPrice
                {
                    UserId     = usChangNew.Id,
                    DateCreate = DateTime.Now,
                    Price      = decimal.Parse(this.tbPrice.Text)
                });
                this._context.SaveChanges();
            }
            if (!string.IsNullOrEmpty(New_FileName))
            {
                var extension = Path.GetExtension(New_FileName);
                var imageName = Path.GetRandomFileName() + extension;
                var dir       = Directory.GetCurrentDirectory();
                var saveDir   = Path.Combine(dir, "images");
                if (!Directory.Exists(saveDir))
                {
                    Directory.CreateDirectory(saveDir);
                }

                var fileSave = Path.Combine(saveDir, imageName);
                File.Copy(New_FileName, fileSave);
                usChangNew.Image = fileSave;
            }


            if (string.IsNullOrEmpty(us.Error))
            {
                MessageBox.Show("Ура, пошло");
                _context.SaveChanges();
            }

            else
            {
                MessageBox.Show(us.Error);
            }

            this.Close();
        }
Ejemplo n.º 16
0
        public void ShouldIgnoreFileThatDoesNotExist()
        {
            var path = IOPath.GetTempPath();

            path = IOPath.Combine(path, IOPath.GetRandomFileName());
            var fileInfo = new CFileInfo(path);

            Assert.That(fileInfo.FileIndex, Is.EqualTo(0));
            Assert.That(fileInfo.LinkCount, Is.EqualTo(0));
            Assert.That(fileInfo.VolumeSerialNumber, Is.EqualTo(0));
        }
        private void ArchivoAbrir()
        {
            OpenFileDialog lxDlg = new OpenFileDialog();

            lxDlg.Filter     = "Todos (*.*)|*.*|Latis (*.latis)|*.latis|Zip (*.zip)|*.zip";
            lxDlg.DefaultExt = ".latis";

            if (lxDlg.ShowDialog() == true)
            {
                string lxNomArch = lxDlg.FileName;
                txtArchLatis.Text = lxNomArch;

                string lxFldrDst = Path.Combine(@"C:\temp\", Path.GetRandomFileName());

                ExtraerTodoslosArchivos(lxNomArch, lxFldrDst);

                string lxCfgFile = Path.Combine(lxFldrDst, CFG_INI);
                string lxCfgText = "";
                if (File.Exists(lxCfgFile))
                {
                    lxCfgText   = File.ReadAllText(lxCfgFile, Encoding.GetEncoding(1252));
                    txtCfg.Text = lxCfgText;
                }

                string lxNomScript = lxCfgText.Split('\n')
                                     .FirstOrDefault(x => x.ToLower().Contains("script"))
                                     .ToString()
                                     .Split('=')[1];

                string lxNomScriptFile = Path.Combine(lxFldrDst, lxNomScript);
                if (!File.Exists(lxNomScriptFile))
                {
                    lxNomScriptFile = Directory.GetFiles(lxFldrDst, "*.sql").FirstOrDefault();
                }


                if (File.Exists(lxNomScriptFile))
                {
                    string lxScriptText = File.ReadAllText(lxNomScriptFile, Encoding.GetEncoding(1252));
                    txtSQL.Text = lxScriptText;
                }

                try
                {
                    //Eliminar directorio temporal
                    Directory.Delete(lxFldrDst, true);
                }
                catch (Exception ex)
                {
                    _ = MessageBox.Show(ex.Message, "Abrir", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
        /// <summary>
        /// Gets the set of search paths by running the interpreter.
        /// </summary>
        /// <param name="interpreter">Path to the interpreter.</param>
        /// <param name="fs">File system services.</param>
        /// <param name="ps">Process services.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>A list of search paths for the interpreter.</returns>
        public static async Task <List <PythonLibraryPath> > GetSearchPathsFromInterpreterAsync(string interpreter, IFileSystem fs, IProcessServices ps, CancellationToken cancellationToken = default)
        {
            // sys.path will include the working directory, so we make an empty
            // path that we can filter out later
            var tempWorkingDir = IOPath.Combine(IOPath.GetTempPath(), IOPath.GetRandomFileName());

            fs.CreateDirectory(tempWorkingDir);
            if (!InstallPath.TryGetFile("get_search_paths.py", out var srcGetSearchPaths))
            {
                return(new List <PythonLibraryPath>());
            }
            var getSearchPaths = IOPath.Combine(tempWorkingDir, PathUtils.GetFileName(srcGetSearchPaths));

            File.Copy(srcGetSearchPaths, getSearchPaths);

            var startInfo = new ProcessStartInfo(
                interpreter,
                new[] { "-S", "-E", getSearchPaths }.AsQuotedArguments()
                )
            {
                WorkingDirectory       = tempWorkingDir,
                UseShellExecute        = false,
                ErrorDialog            = false,
                CreateNoWindow         = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true
            };

            try {
                var output = await ps.ExecuteAndCaptureOutputAsync(startInfo, cancellationToken);

                return(output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(s => {
                    try {
                        var p = Parse(s);

                        if (PathUtils.PathStartsWith(p.Path, tempWorkingDir))
                        {
                            return null;
                        }

                        return p;
                    } catch (ArgumentException) {
                        Debug.Fail("Invalid search path: " + (s ?? "<null>"));
                        return null;
                    } catch (FormatException) {
                        Debug.Fail("Invalid format for search path: " + s);
                        return null;
                    }
                }).Where(p => p != null).ToList());
            } finally {
                fs.DeleteDirectory(tempWorkingDir, true);
            }
        }
Ejemplo n.º 19
0
        private static string GetTempDirPath([CanBeNull] string tempDirName)
        {
            if (tempDirName == null)
            {
                tempDirName = Path.GetDirectoryName(Path.GetRandomFileName());

                Assert.NotNull(tempDirName);
            }

            string localTempDir = Path.Combine(Path.GetTempPath(), tempDirName);

            return(localTempDir);
        }
Ejemplo n.º 20
0
        public void Should_Download_Asset(string assetUri)
        {
            var tempFile = Path.GetTempFileName();

            _server.Stub(x => x.Get(assetUri))
            .ReturnFile(tempFile)
            .OK();

            var asset      = new ProGetAssetDownloader(_config);
            var outputPath = Path.GetRandomFileName();

            asset.GetSingleAsset($"{Host}{assetUri}", outputPath);
            Assert.True(File.Exists(outputPath));
            File.Delete(outputPath);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Returns a temp <see cref="T:System.Uri"/>.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Uri" /> file.
        /// </returns>
        public static Uri GetUniqueTempRandomFile()
        {
            Logger.Instance.Debug("");
            Logger.Instance.Debug(" Assembly: iTin.Core.IO, Namespace: iTin.Core.IO, Class: File");
            Logger.Instance.Debug($" Returns a temp {typeof(Uri)}");
            Logger.Instance.Debug($" > Signature: ({typeof(Uri)}) GetUniqueTempRandomFile()");

            string tempPath       = NativePath.GetTempPath();
            string randomFileName = NativePath.GetRandomFileName();
            string path           = NativePath.Combine(tempPath, randomFileName);

            Logger.Instance.Debug($"  > Output: {path}");

            return(new Uri(path));
        }
        public void Should_Download_Asset(string assetUri)
        {
            using (var server = FluentMockServer.Start())
            {
                var tempFile = Path.GetTempFileName();

                server.Given(Request.Create().WithPath(assetUri).UsingGet())
                .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK).WithBodyFromFile(tempFile));

                var asset      = new ProGetAssetDownloader(_config);
                var outputPath = Path.GetRandomFileName();
                asset.GetSingleAsset($"http://localhost:{server.Ports[0]}{assetUri}", outputPath);
                Assert.True(File.Exists(outputPath));
                File.Delete(outputPath);
            }
        }
Ejemplo n.º 23
0
        public void Should_Throw_Exception_When_Asset_Push_Fails_As_Put(string assetUri)
        {
            _server.Stub(x => x.Put(assetUri))
            .WithStatus(HttpStatusCode.BadRequest);

            var asset    = new ProGetAssetPusher(_log, _config);
            var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");

            using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                fileStream.SetLength(4194304);
            }
            var result = Record.Exception(() => asset.Publish(tempFile, $"{Host}{assetUri}"));

            File.Delete(tempFile.FullPath);
            Assert.IsCakeException(result, "Upload failed. This request would have overwritten an existing package.");
        }
Ejemplo n.º 24
0
        public void Should_Push_New_Asset_With_Put_Under_5MB(string assetUri)
        {
            _server.Stub(x => x.Put(assetUri))
            .OK();

            var asset    = new ProGetAssetPusher(_log, _config);
            var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");

            using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
            {
                fileStream.SetLength(4194304);
            }
            var result = Record.Exception(() => asset.Publish(tempFile, $"{Host}{assetUri}"));

            File.Delete(tempFile.FullPath);
            Assert.Null(result);
        }
Ejemplo n.º 25
0
        public void ShouldGetFileInfo()
        {
            var path = IOPath.GetTempPath();

            path = IOPath.Combine(path, IOPath.GetRandomFileName());
            var file = IOFile.Create(path);

            file.Close();
            try
            {
                var fileInfo = new CFileInfo(path);
                BY_HANDLE_FILE_INFORMATION kernelFileInfo;
                using (file = IOFile.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    try
                    {
                        CFileInfo.GetFileInformationByHandle(file.SafeFileHandle, out kernelFileInfo);
                    }
                    finally
                    {
                        file.Close();
                    }
                }

                Assert.That(fileInfo.LinkCount, Is.EqualTo(kernelFileInfo.NumberOfLinks), "LinkCount");
                Assert.That(fileInfo.VolumeSerialNumber, Is.EqualTo(kernelFileInfo.VolumeSerialNumber), "VolumeSerialNumber");

                UInt64 fileIndex = kernelFileInfo.FileIndexHigh;
                fileIndex  = fileIndex << 32;
                fileIndex |= kernelFileInfo.FileIndexLow;

                Assert.That(fileInfo.FileIndex, Is.EqualTo(fileIndex), "FileIndex");

                fileIndex = fileInfo.FileIndex;
                var upperIndex = (uint)((fileIndex >> 32) & 0xffffffff);
                Assert.That(kernelFileInfo.FileIndexHigh, Is.EqualTo(upperIndex));

                var lowerIndex = (uint)(fileIndex & 0xffffffff);
                Assert.That(kernelFileInfo.FileIndexLow, Is.EqualTo(lowerIndex));
            }
            finally
            {
                IOFile.Delete(path);
            }
        }
        public void Should_Push_New_Asset_With_Multipart_Post_Over_5MB(string assetUri)
        {
            using (var server = FluentMockServer.Start())
            {
                server.Given(Request.Create().WithPath(assetUri).UsingPost())
                .RespondWith(Response.Create().WithStatusCode(HttpStatusCode.OK));

                var asset    = new ProGetAssetPusher(_log, _config);
                var tempFile = new FilePath($"{Path.GetTempPath()}{Path.GetRandomFileName()}");
                using (var fileStream = new FileStream(tempFile.FullPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    fileStream.SetLength(6291456);
                }
                var result = Record.Exception(() => asset.Publish(tempFile, $"http://localhost:{server.Ports[0]}{assetUri}"));
                File.Delete(tempFile.FullPath);
                Assert.Null(result);
            }
        }
Ejemplo n.º 27
0
 private static bool IsDirectoryWritable(string path)
 {
     try
     {
         if (!Directory.Exists(path))
         {
             return(false);
         }
         string file = System_IO_Path.Combine(path, System_IO_Path.GetRandomFileName());
         using (FileStream fs = File.Create(file, 1)) { }
         File.Delete(file);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Ejemplo n.º 28
0
        private void ImportSkinPackButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Filter = "MCPACK Files (*.mcpack)|*.mcpack|ZIP Files (*.zip)|*.zip"
            };

            if (dialog.ShowDialog().Value)
            {
                try
                {
                    var file = ZipFile.OpenRead(dialog.FileName);
                    if (file.Entries.ToList().Exists(x => x.FullName == "skins.json"))
                    {
                        file.Dispose();
                        string InstallationPath     = Filepaths.GetInstallationsFolderPath(ConfigManager.CurrentProfile, ConfigManager.CurrentInstallation.DirectoryName);
                        string NewPackDirectoryName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                        string NewPackDirectory     = Path.Combine(Filepaths.GetSkinPacksFolderPath(InstallationPath, false), NewPackDirectoryName);

                        while (Directory.Exists(NewPackDirectory))
                        {
                            NewPackDirectoryName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
                            NewPackDirectory     = Path.Combine(Filepaths.GetSkinPacksFolderPath(InstallationPath, false), NewPackDirectoryName);
                        }

                        ZipFile.ExtractToDirectory(dialog.FileName, NewPackDirectory);
                    }
                    else
                    {
                        file.Dispose();
                        ErrorScreenShow.errormsg("notaskinpack");
                    }
                }
                catch (Exception ex)
                {
                    ErrorScreenShow.exceptionmsg(ex);
                }
            }
            ReloadSkinPacks();
        }
Ejemplo n.º 29
0
        private async Task RunAsync()
        {
            var items   = listFiles.Items.OfType <string>().ToList();
            var outpath = textPath.Text;

            SetProgress(1, "正在创建临时文件夹");
            var tempFolder = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            LogDebugInfo($"临时文件夹: {tempFolder}");
            Directory.CreateDirectory(tempFolder);


            var ffmpeg          = Path.Combine(AppContext.BaseDirectory, "lib", "ffmpeg.exe");
            var filelistBuilder = new StringBuilder();

            for (int i = 0; i < items.Count; i++)
            {
                SetProgress(1 + 59 * i / (double)items.Count, $"正在转换第{i}/{items.Count}个视频");

                var filename = Path.Combine(tempFolder, $"{i}.mp4");
                filelistBuilder.AppendLine($"file '{filename}'");

                var subprocess = Process.Start(ffmpeg, $"-i \"{items[i]}\" -af apad -c:v copy -c:a aac -b:a 256k -shortest \"{filename}\"");
                await subprocess.WaitForExitAsync();
            }

            var filelistPath = Path.Combine(tempFolder, "filelist");

            File.WriteAllText(filelistPath, filelistBuilder.ToString());

            var combineProcess = Process.Start(ffmpeg, $"-f concat -safe 0 -i \"{filelistPath}\" -c copy \"{outpath}\"");
            await combineProcess.WaitForExitAsync();

            SetProgress(99, "正在清理临时文件");
            Directory.Delete(tempFolder, recursive: true);

            SetProgress(100, "任务已完成");
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Creates a new temporary directory.
        /// </summary>
        /// <param name="prefix">a prefix to give to the directory's name</param>
        /// <exception cref="IOException">if there is an error creating the directory</exception>
        public TempDir(string prefix)
        {
            try
            {
                do
                {
                    string filename = (String.IsNullOrEmpty(prefix)) ? "" : prefix + ".";
                    filename += IOPath.GetRandomFileName();
                    Info      = new DirectoryInfo(IOPath.Combine(IOPath.GetTempPath(), filename));
                }while (Info.Exists);

                Info.Create();
                Info.Refresh();
            }
            catch (UnauthorizedAccessException uae)
            {
                throw new IOException(uae.Message, uae);
            }
            catch (System.Security.SecurityException se)
            {
                throw new IOException(se.Message, se);
            }
        }