ChangeExtension() 공개 정적인 메소드

public static ChangeExtension ( string path, string extension ) : string
path string
extension string
리턴 string
예제 #1
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));
        }
예제 #2
0
        private void OpenExhaustedReasons(string fileName)
        {
            string info = Path.ChangeExtension(fileName, ".exh");

            if (File.Exists(info))
            {
                using (StreamReader r = new StreamReader(File.Open(info, FileMode.Open)))
                {
                    var reasons = r.ReadToEnd();

                    foreach (var reason in reasons.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                    {
                        if (reason != "")
                        {
                            var chunks       = reason.Split('|');
                            var number       = Int32.Parse(chunks[0]);
                            var reasonString = chunks[1];


                            exhaustedReasons.Add(number, reasonString);
                        }
                    }
                }
            }
        }
예제 #3
0
        public void NewProject()
        {
            using (var app = new PythonVisualStudioApp()) {
                using (var newProjDialog = NewProjectDialog.FromDte(app)) {
                    newProjDialog.FocusLanguageNode();

                    var consoleApp = newProjDialog.ProjectTypes.FindItem("Python Application");
                    consoleApp.Select();

                    newProjDialog.OK();
                }

                // wait for new solution to load...
                for (int i = 0; i < 10 && app.Dte.Solution.Projects.Count == 0; i++)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                Assert.AreEqual(1, app.Dte.Solution.Projects.Count);

                var project = app.Dte.Solution.Projects.Item(1);
                Console.WriteLine("Project.Name: {0}", project.Name ?? "(null)");

                var itemName = Path.ChangeExtension(project.Name, ".py");
                Console.WriteLine("Expected item: {0}", itemName);

                Console.WriteLine("Items:");
                foreach (var item in project.ProjectItems.OfType <ProjectItem>())
                {
                    Console.WriteLine("  {0}", item.Name ?? "(null)");
                }

                Assert.IsNotNull(project.ProjectItems.Item(itemName));
            }
        }
예제 #4
0
        public MainWindow()
        {
            App    applic = (App)(App.Current);
            String source = string.Empty;
            string dest   = string.Empty;

            if (applic.Arguments.Length > 0)
            {
                source = applic.Arguments[0];
                dest   = Path.ChangeExtension(source, ".epub");
            }
            this.InitializeComponent();
            Options = new ConversionOptions()
            {
                SourceFilename      = source,
                DestinationFilename = dest,
                MaxSplitSizeInBytes = 100 * 1024,
                StripHeader         = new Pattern()
                {
                    Enable    = true,
                    LineCount = 2,
                    RegEx     = EncodeString("(<b>[IVX0-9]*?</b><br>\r\n[^<]*?<br>\r\n)|([^<]*?<br>\r\n<b>[IVX0-9]*?</b><br>\r\n)")
                },
                StripFooter = new Pattern()
                {
                    Enable    = true,
                    LineCount = 1,
                    RegEx     = EncodeString("<b>[IVX0-9]*?</b><br>")
                }
            };
            DataContext = Options;
        }
예제 #5
0
        private void OnConvertFtcxClick(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog {
                    Filter = "FFX Picture (*.ftcx)|*.ftcx", Multiselect = true
                };
                if (dlg.ShowDialog() != true)
                {
                    return;
                }

                foreach (string filePath in dlg.FileNames)
                {
                    using (FileStream input = File.OpenRead(filePath))
                    {
                        FtcxFileReader fileReader = new FtcxFileReader(input);
                        FtcxFileHeader header     = fileReader.ReadHeader();
                        int            width      = header.BlockSize * 2;
                        short          height     = header.BlockCount;
                        fileReader.SkipUnknownSubHeader();
                        using (SafeHGlobalHandle image = fileReader.ReadImage())
                            using (UnmanagedMemoryStream imageInput = image.OpenStream(FileAccess.Read))
                                using (FileStream output = File.Create(Path.ChangeExtension(filePath, String.Format(".{0}x{1}.raw", width, height))))
                                    imageInput.CopyTo(output);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
예제 #6
0
        private void BatchExportTranslationMenuItem_Click(object sender, RoutedEventArgs e)
        {
            var sfd = new SaveFileDialog
            {
                Filter   = GenerateFilters(false),
                FileName = "Select a file type and folder to store all the text files and press Save",
                Title    = "Batch Export"
            };

            if (sfd.ShowDialog() == true)
            {
                // Path to the directory which will contain all the translation files
                string dir = Path.GetDirectoryName(sfd.FileName);
                // Gets the index of the filetype
                var index = sfd.FilterIndex - 1;
                foreach (var entry in ScriptArchive.FileEntries)
                {
                    var script = new STSCFile();
                    using (var stream = ScriptArchive.GetFileStream(entry.FileName))
                        script.Load(stream);
                    string filepath = Path.ChangeExtension(Path.Combine(dir, entry.FileName),
                                                           TranslationSTSCHandler.FileTypes[index].TypeExtension);
                    // Create the directory
                    Directory.CreateDirectory(Path.GetDirectoryName(filepath));
                    File.WriteAllText(filepath, TranslationSTSCHandler.ExportTranslation(index, script, ScriptDB, App.StringProcess), new UTF8Encoding(true));
                }
            }
        }
예제 #7
0
파일: Batch.cs 프로젝트: NCC-Lykos/Chisel
        private void DoBatch()
        {
            var logFile   = Path.ChangeExtension(TargetFile, ".log");
            var batchFile = Path.ChangeExtension(TargetFile, ".bat");
            var batch     = "";

            batch += "cd " + '"' + Path.GetDirectoryName(TargetFile) + '"' + "\n";
            foreach (var step in Steps)
            {
                batch += '"' + step.Operation + '"' + ' ' + step.Flags + "\n";
            }
            File.WriteAllText(batchFile, batch);

            var process = new Process
            {
                StartInfo = new ProcessStartInfo(batchFile)
                {
                    WorkingDirectory = Path.GetDirectoryName(TargetFile)
                }
            };

            CompileLogTracer.AddLine("Compile started (not redirected; output in console window)");
            process.Start();
            process.WaitForExit();
            if (File.Exists(logFile))
            {
                using (var fs = new StreamReader(File.Open(logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
                {
                    var str = fs.ReadToEnd();
                    CompileLogTracer.Add(str);
                }
            }
            CompileLogTracer.AddLine("Compilation complete.");
        }
예제 #8
0
        void buttonDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridSaves.SelectedRows;

            if (selectedRows.Count > 0)
            {
                gridSaves.ClearSelection();

                if (!Directory.Exists(UserSettings.DeletedSaveFolder))
                {
                    Directory.CreateDirectory(UserSettings.DeletedSaveFolder);
                }

                for (var i = 0; i < selectedRows.Count; i++)
                {
                    var save = selectedRows[i].DataBoundItem as Save;
                    foreach (var fileName in new[] { Path.GetFileName(save.File), Path.ChangeExtension(Path.GetFileName(save.File), "png") })
                    {
                        try
                        {
                            File.Move(Path.Combine(UserSettings.UserDataFolder, fileName), Path.Combine(UserSettings.DeletedSaveFolder, fileName));
                        }
                        catch { }
                    }
                }

                LoadSaves();
            }
        }
예제 #9
0
        void buttonDeleteInvalid_Click(object sender, EventArgs e)
        {
            gridSaves.ClearSelection();

            var directory = UserSettings.UserDataFolder;

            if (Directory.Exists(directory))
            {
                var deletes = 0;
                foreach (var saveFile in Directory.GetFiles(directory, "*.save"))
                {
                    var save = new Save(saveFile, Settings.YoungestVersionFailedToRestore);
                    if (save.Valid == false)
                    {
                        foreach (var fileName in new[] {
                            save.File,
                            Path.ChangeExtension(save.File, "png"),
                            Path.ChangeExtension(save.File, "txt"),
                            Path.ChangeExtension(save.File, "replay")
                        }
                                 )
                        {
                            try
                            {
                                File.Delete(fileName);
                            }
                            catch { }
                        }
                        deletes++;
                    }
                }
                MessageBox.Show(catalog.GetStringFmt("{0} invalid saves have been deleted.", deletes), Application.ProductName + " " + VersionInfo.VersionOrBuild);
            }
            LoadSaves();
        }
        public async void Play(Uri file)
        {
            vlcPlayer.LoadMedia(file);
            _cdgFile = await GraphicsFile.LoadAsync(Path.ChangeExtension(file.LocalPath, "cdg"));

            vlcPlayer.Play();
        }
예제 #11
0
        public static void RunTestExample <T>(string filePartName)
            where T : IXLExample, new()
        {
            // Make sure tests run on a deterministic culture
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            var example = new T();

            string[] pathParts = filePartName.Split(new char[] { '\\' });
            string   filePath1 = Path.Combine(new List <string>()
            {
                TestsExampleOutputDirectory
            }.Concat(pathParts).ToArray());

            var extension = Path.GetExtension(filePath1);
            var directory = Path.GetDirectoryName(filePath1);

            var fileName = Path.GetFileNameWithoutExtension(filePath1);

            fileName += ActualTestResultPostFix;
            fileName  = Path.ChangeExtension(fileName, extension);

            filePath1 = Path.Combine(directory, "z" + fileName);
            var filePath2 = Path.Combine(directory, fileName);

            //Run test
            example.Create(filePath1);
            new XLWorkbook(filePath1).SaveAs(filePath2, true);
            bool success = true;

#pragma warning disable 162
            try
            {
                //Compare
                // ReSharper disable ConditionIsAlwaysTrueOrFalse
                if (CompareWithResources)
                // ReSharper restore ConditionIsAlwaysTrueOrFalse

                {
                    string resourcePath = filePartName.Replace('\\', '.').TrimStart('.');
                    using (var streamExpected = _extractor.ReadFileFromResToStream(resourcePath))
                        using (var streamActual = File.OpenRead(filePath2))
                        {
                            string message;
                            success = ExcelDocsComparer.Compare(streamActual, streamExpected, TestHelper.IsRunningOnUnix, out message);
                            var formattedMessage =
                                String.Format(
                                    "Actual file '{0}' is different than the expected file '{1}'. The difference is: '{2}'",
                                    filePath2, resourcePath, message);

                            Assert.IsTrue(success, formattedMessage);
                        }
                }
            }
            finally
            {
                //if (success && File.Exists(filePath)) File.Delete(filePath);
            }
#pragma warning restore 162
        }
예제 #12
0
        /// <summary>
        /// 复制文件(夹)(每次一条信息/文件)
        /// </summary>
        /// <param name="info">音乐信息</param>
        /// <returns>复制到的文件目录(包含文件名)</returns>
        private string CopyFileFunc(MusicInfo info)
        {
            string finalPath;

            if (isCopyFolder)
            {
                string   relativeAddr = info.Path.Split(new string[] { ChoiseAddr }, StringSplitOptions.None)[1];
                string[] minAddr      = ChoiseAddr.Split(new char[] { '\\' });
                finalPath = rootPath + @"\Music\" + minAddr[minAddr.Length - 1] + relativeAddr;
                CreatePath(Path.GetDirectoryName(finalPath));
            }
            else
            {
                if (Setting.Default.BuildFolderMode == 0)
                {
                    finalPath = rootPath + @"\Music\" + Path.GetFileName(info.Path);
                }
                else if (Setting.Default.BuildFolderMode == 1)
                {
                    finalPath = CheckArtist(info, rootPath) + "\\" + Path.GetFileName(info.Path);
                }
                else
                {
                    finalPath = CheckAlbum(info, rootPath) + "\\" + Path.GetFileName(info.Path);
                }
            }

            File.Copy(info.Path, finalPath);
            if (CheckLyric(info.Path))
            {
                File.Copy(Path.ChangeExtension(info.Path, "lrc"), Path.ChangeExtension(finalPath, "lrc"));
            }
            return(finalPath);
        }
예제 #13
0
        static string ConvertAig(AlImage img, string path)
        {
            foreach (var converter in imageConverters)
            {
                if (converter.CanConvert(img.PixelFormat))
                {
                    string outPath = Path.ChangeExtension(path, converter.FileExtension);
                    using (FileStream ofs = File.Create(outPath))
                    {
                        converter.ConvertFromAl(img, ofs);
                    }
                    if (converter.HasAlternativeFile(img))
                    {
                        outPath = Path.ChangeExtension(path, null);
                        outPath = $"{outPath}_alt{converter.FileExtension}";
                        using (FileStream ofs = File.Create(outPath))
                        {
                            converter.ConvertFromAlAlt(img, ofs);
                        }
                    }
                    return(converter.FileExtension);
                }
            }

            throw new Exception($"Cannot find converter for {img.PixelFormat}");
        }
예제 #14
0
        public static Stream LoadNMSFileStream(string filepath, ref ResourceManager resMgr)
        {
            int load_mode = 0;

            string conv_filepath = filepath.TrimStart('/');

            filepath = filepath.Replace('\\', '/');
            string effective_filepath = filepath;

            string exmlpath = Path.ChangeExtension(filepath, "exml");

            exmlpath = exmlpath.ToUpper(); //Make upper case

            if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, exmlpath)))
            {
                load_mode = 0; //Load Exml
            }
            else if (File.Exists(Path.Combine(RenderState.settings.UnpackDir, filepath)))
            {
                load_mode = 1; //Load MBIN from file
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey(filepath))
            {
                load_mode = 2; //Extract file from archive
            }
            else if (resMgr.NMSFileToArchiveMap.ContainsKey("/" + filepath))
            {
                effective_filepath = "/" + filepath;
                load_mode          = 2; //Extract file from archive
            }
            else
            {
                CallBacks.Log("File: " + filepath + " Not found in PAKs or local folders. ");
                Util.showError("File: " + filepath + " Not found in PAKs or local folders. ", "Error");
                throw new FileNotFoundException("File not found\n " + filepath);
            }
            switch (load_mode)
            {
            case 0:     //Load EXML
                return(new FileStream(Path.Combine(RenderState.settings.UnpackDir, exmlpath), FileMode.Open));

            case 1:     //Load MBIN
                return(new FileStream(Path.Combine(RenderState.settings.UnpackDir, filepath), FileMode.Open));

            case 2:     //Load File from Archive
            {
                CallBacks.Log("Trying to export File" + effective_filepath);
                if (resMgr.NMSFileToArchiveMap.ContainsKey(effective_filepath))
                {
                    CallBacks.Log("File was found in archives. File Index: " + resMgr.NMSFileToArchiveMap[effective_filepath].GetFileIndex(effective_filepath));
                }

                int fileIndex = resMgr.NMSFileToArchiveMap[effective_filepath].GetFileIndex(effective_filepath);
                return(resMgr.NMSFileToArchiveMap[effective_filepath].ExtractFile(fileIndex));
            }
            }

            return(null);
        }
예제 #15
0
    public PythonScript(string filename, string content, PythonAst ast)
    {
        Filename  = filename;
        Namespace = "Scripts";
        ClassName = CreateClassName(Path.ChangeExtension(filename, null));
        Content   = content;
        AST       = ast;

        Type       = ScriptType.Module;
        ScriptId   = -1;
        OutputPath = ClassName + ".cs";

        // Check if the filename matches the pattern for "attached" scripts that will contain san_ events.
        var match = PythonScriptNamePattern.Match(filename);

        if (match.Success)
        {
            Type       = ScriptType.Object;
            ScriptId   = int.Parse(match.Groups[1].Value);
            ClassName  = CreateClassName(match.Groups[2].Value);
            OutputPath = ClassName + ".cs";
            Namespace  = "Scripts";
        }
        else
        {
            match = SpellNamePattern.Match(filename);
            if (match.Success)
            {
                Type       = ScriptType.Spell;
                SpellId    = int.Parse(match.Groups[1].Value);
                ClassName  = CreateClassName(match.Groups[2].Value);
                OutputPath = "Spells/" + ClassName + ".cs";
                Namespace  = "Scripts.Spells";
            }
        }

        // Find imported modules
        var importedWalker = new ImportedModulesWalker();

        ast.Walk(importedWalker);
        ImportedModules = importedWalker.ImportedModules;
        ImportedModules.Remove("toee");
        ImportedModules.Remove("__main__");
        ImportedModules.Remove("math");
        ImportedModules.Remove("sys");
        ImportedModules.Remove("array");
        ImportedModules.Remove("t"); // because it has a circular dependency
        ImportedModules.Remove("co8Util");
        ImportedModules.Remove("co8Util.Logger");
        ImportedModules.Remove("co8Util.PersistentData");
        ImportedModules.Remove("co8Util.TimedEvent");
        ImportedModules.Remove("co8Util.ObjHandling");
        ImportedModules.Remove("co8Util.Enum");
        ImportedModules.Remove("_include"); // Co8 hack
        if (ModuleName != "utilities")
        {
            ImportedModules.Add("utilities"); // Implicitly imported by C++ code into __main__
        }
    }
예제 #16
0
        static string GetWorkflowPath(string path)
        {
            if (SystemPath.GetExtension(path) == string.Empty)
            {
                return(SystemPath.ChangeExtension(path, Constants.BonsaiExtension));
            }

            return(path);
        }
예제 #17
0
 static void BulkConvertTxm(string inPath, string filter, bool recursive)
 {
     foreach (var path in Directory.GetFiles(inPath, filter, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly))
     {
         string outPath = Path.ChangeExtension(path, ".png");
         Console.WriteLine(outPath);
         ConvertTxm(path);
     }
 }
예제 #18
0
        private void BatchImportTranslationMenuItem_Click(object sender, RoutedEventArgs e)
        {
            string tag = ((MenuItem)sender)?.Tag as string;
            var    sfd = new SaveFileDialog
            {
                Filter   = GenerateFilters(false),
                FileName = "Select a file type and the folder which contains the translation files (the folder containing the 1st, 2nd and 3rd folder) and press Save",
                Title    = "Batch Import"
            };

            if (sfd.ShowDialog() == true)
            {
                // Path to the directory which contains all the translation files
                string dir = Path.GetDirectoryName(sfd.FileName);
                // Gets the index of the filetype
                int index = sfd.FilterIndex - 1;
                foreach (var entry in ScriptArchive.FileEntries)
                {
                    var script = new STSCFile();
                    using (var stream = ScriptArchive.GetFileStream(entry.FileName))
                        script.Load(stream);
                    // Path to the script file
                    string filepath = Path.ChangeExtension(Path.Combine(dir, entry.FileName), TranslationSTSCHandler.FileTypes[index].TypeExtension);
                    // Skip script if file does not exist
                    if (!File.Exists(filepath))
                    {
                        continue;
                    }
                    // Import translation
                    try
                    {
                        string data = "";
                        using (var stream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            using (StreamReader reader = new StreamReader(stream))
                                data = reader.ReadToEnd();
                        TranslationSTSCHandler.ImportTranslation(index, script, data, !tag.Contains("nokey"), App.StringProcess);
                        // Save the script back into the archive
                        using (var stream = new MemoryStream())
                        {
                            script.Save(stream);
                            ScriptArchive.ReplaceFile(entry.FileName, stream.ToArray());
                        }
                    }
                    catch
                    {
                        MessageBox.Show("Failed to open file! Possible another program is using it.", "Import Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            // Reload the current script
            if (ScriptListBox.SelectedIndex == -1)
            {
                return;
            }
            LoadScript(ScriptArchive.FileEntries[ScriptListBox.SelectedIndex].FileName);
        }
예제 #19
0
파일: UploadFile.cs 프로젝트: zzattack/NFU
        public UploadFile(FileState state = FileState.Normal, string extension = null)
        {
            State = state;

            if (state == FileState.Temporary)
            {
                Path     = IOPath.GetTempFileName();
                FileName = IOPath.ChangeExtension(FileName, extension);
            }
        }
예제 #20
0
        public void Convert1()
        {
            var testRootDir = TestContext.WorkDirectory;
            var xpsFile     = Path.Combine(testRootDir, "XpsConverterTest/xps", "page1.xps");
            var pdfFile     = Path.ChangeExtension(xpsFile, ".pdf");

            XpsConverter.Convert(xpsFile);

            Assert.IsTrue(File.Exists(pdfFile));
        }
예제 #21
0
 static void ConvertTxm(string path, string outPath = null)
 {
     using (Stream fs = Utils.CheckDecompress(File.OpenRead(path)))
     {
         if (outPath == null)
         {
             outPath = Path.ChangeExtension(path, ".png");
         }
         TxmConversion.ConvertTxmToPng(fs, outPath);
     }
 }
예제 #22
0
        public bool ChangeExtension(string extension)
        {
            BuildExceptions.NotNullNotEmpty(extension, "extension");
            if (this.IsValid)
            {
                _path = IoPath.ChangeExtension(_path, extension);

                return(true);
            }

            return(false);
        }
예제 #23
0
        public static NMSTemplate LoadNMSFileOLD(string filepath)
        {
            int         load_mode = 0;
            NMSTemplate template;

            string exmlpath = Path.ChangeExtension(filepath, "exml");

            exmlpath = exmlpath.ToUpper(); //Make upper case

            if (File.Exists(exmlpath))
            {
                load_mode = 0;
            }
            else
            {
                load_mode = 1;
            }


            //Load Exml
            try
            {
                if (load_mode == 0)
                {
                    string xml = File.ReadAllText(exmlpath);
                    template = EXmlFile.ReadTemplateFromString(xml);
                }
                else
                {
                    if (!File.Exists(filepath))
                    {
                        throw new FileNotFoundException("File not found\n " + filepath);
                    }
                    libMBIN.MBINFile mbinf = new libMBIN.MBINFile(filepath);
                    mbinf.Load();
                    template = mbinf.GetData();
                    mbinf.Dispose();
                }
            } catch (Exception ex)
            {
                if (ex is System.IO.DirectoryNotFoundException || ex is System.IO.FileNotFoundException)
                {
                    Util.showError("File " + filepath + " Not Found...", "Error");
                }
                else if (ex is System.Reflection.TargetInvocationException)
                {
                    Util.showError("libMBIN failed to decompile the file. Try to update the libMBIN.dll (File->updateLibMBIN). If the issue persists contact the developer", "Error");
                }
                return(null);
            }

            return(template);
        }
        public static void RunTestExample <T>(string filePartName, bool evaluateFormulae = false)
            where T : IXLExample, new()
        {
            // Make sure tests run on a deterministic culture
            Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

            var example = new T();

            string[] pathParts = filePartName.Split(new char[] { '\\' });
            string   filePath1 = Path.Combine(new List <string>()
            {
                ExampleTestsOutputDirectory
            }.Concat(pathParts).ToArray());

            var extension = Path.GetExtension(filePath1);
            var directory = Path.GetDirectoryName(filePath1);

            var fileName = Path.GetFileNameWithoutExtension(filePath1);

            fileName += ActualTestResultPostFix;
            fileName  = Path.ChangeExtension(fileName, extension);

            filePath1 = Path.Combine(directory, "z" + fileName);
            var filePath2 = Path.Combine(directory, fileName);

            //Run test
            example.Create(filePath1);
            using (var wb = new XLWorkbook(filePath1))
                wb.SaveAs(filePath2, validate: true, evaluateFormulae);

            // Also load from template and save it again - but not necessary to test against reference file
            // We're just testing that it can save.
            using (var ms = new MemoryStream())
                using (var wb = XLWorkbook.OpenFromTemplate(filePath1))
                    wb.SaveAs(ms, validate: true, evaluateFormulae);

            if (CompareWithResources)
            {
                string resourcePath = "Examples." + filePartName.Replace('\\', '.').TrimStart('.');
                using (var streamExpected = _extractor.ReadFileFromResourceToStream(resourcePath))
                    using (var streamActual = File.OpenRead(filePath2))
                    {
                        var success          = ExcelDocsComparer.Compare(streamActual, streamExpected, out string message);
                        var formattedMessage =
                            String.Format(
                                "Actual file '{0}' is different than the expected file '{1}'. The difference is: '{2}'",
                                filePath2, resourcePath, message);

                        Assert.IsTrue(success, formattedMessage);
                    }
            }
        }
        /// <summary>
        ///     Creates the encrypted archive.
        /// </summary>
        /// <param name="selectedFolder">The selected folder.</param>
        /// <param name="archiveName">Name of the archive.</param>
        /// <externalUnit/>
        /// <revision revisor="dev13" date="11/18/2009" version="1.1.3.6">
        ///     Added documentation header
        /// </revision>
        private void CreateEncryptedArchive(
            string selectedFolder, string archiveName)
        {
            try
            {
                string publicKey = string.Empty;

                string archiveFileName =
                    string.IsNullOrEmpty(archiveName)
                    ? "TestEncryptedArchive"
                    : archiveName;
                string fullArchiveFilename = archiveFileName + ".zip";
                using (var encryptedArchive = new EncryptedArchive(
                           selectedFolder,
                           fullArchiveFilename,
                           new SequoiaCryptoProvider()))
                {
                    encryptedArchive.OpenWrite(DateTime.Now, true);
                    foreach (
                        string pathName in Directory.GetFiles(selectedFolder))
                    {
                        string fileName = System.IO.Path.GetFileName(pathName);

                        if (fileName == fullArchiveFilename)
                        {
                            continue;
                        }

                        // encryptedArchive.AddFile(fileName);
                        byte[] fileData = File.ReadAllBytes(pathName);

                        encryptedArchive.AddFile(fileData, fileName);
                    }
                }

                var sequoiaProvider = new SequoiaCryptoProvider();
                sequoiaProvider.CreateSignature(
                    Path.Combine(
                        selectedFolder,
                        Path.ChangeExtension(fullArchiveFilename, "enc")));
            }
            catch (Exception exception)
            {
                MessageBox.Show(
                    string.Format(
                        "Error creating encrypted archive: {0}",
                        exception.Message),
                    "Encrypted Archive Creation Failure",
                    MessageBoxButton.OK,
                    MessageBoxImage.Error);
            }
        }
예제 #26
0
        private void ButtonSource_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.Filter = "Portable Document Files|*.pdf";
            bool?result = dialog.ShowDialog();

            if (result == true)
            {
                Options.SourceFilename      = dialog.FileName;
                Options.DestinationFilename = Path.ChangeExtension(Options.SourceFilename, ".epub");
            }
        }
예제 #27
0
        static void ExtractBg(string bgPath, string basePath = null)
        {
            if (basePath == null)
            {
                basePath = Path.ChangeExtension(bgPath, null);
            }
            else
            {
                basePath = Path.Combine(basePath, Path.GetFileNameWithoutExtension(bgPath));
            }

            DatReader dat = new DatReader(Utils.CheckDecompress(File.OpenRead(bgPath)));

            using ObjConverter converter = new ObjConverter(dat);
            string mtlPath = basePath + ".mtl";
            string mtlName = Path.GetFileName(mtlPath);

            for (int i = 0; i < 3; ++i)
            {
                using MemoryStream ms = new MemoryStream(dat.GetData(i));
                DatReader innerDat = new DatReader(ms);
                for (int j = 0; j < innerDat.EntriesCount; ++j)
                {
                    using BinaryReader br = new BinaryReader(new MemoryStream(innerDat.GetData(j)));
                    Tdb tdb = new Tdb();
                    tdb.Read(br);

                    // Remap textures (only known for Windows version, PS2 todo when files obtained)
                    if (i == 0)
                    {
                        tdb.Textures[0].DatIndex = 4;
                        tdb.Textures[1].DatIndex = 3;
                    }
                    else
                    {
                        tdb.Textures[0].DatIndex = 5;
                    }

                    using StreamWriter sw = File.CreateText($"{basePath}.{i}_{j}.obj");
                    sw.WriteLine($"mtllib {mtlName}");
                    sw.WriteLine();

                    converter.ConvertObj(tdb, sw);
                }
            }

            using (StreamWriter sw = File.CreateText(mtlPath))
            {
                converter.ExportTextures(sw, basePath + ".", true);
            }
        }
        private static void Convert(Options options)
        {
            var converter = new SvgToVectorDocumentConverter(options.BlankVectorDrawablePath, options.FixFillType);

            foreach (var inputFile in Directory.GetFiles(options.InputDirectory, options.InputMask + ".pdf", SearchOption.AllDirectories))
            {
                Console.Write(".");

                var subpath  = PathHelper.Subpath(inputFile, options.InputDirectory);
                var tempFile = PathHelper.GenerateTempFileName("svg");

                try
                {
                    Inkscape.ConvertPdfToSvg(Inkscape.FindAppPath(), inputFile, tempFile);

                    SvgO.OptimizeSvg(options.SvgOPath, tempFile, tempFile);
                    SvgPreprocessor.Preprocess(tempFile, tempFile);

                    var svgDocument    = SvgDocumentWrapper.CreateFromFile(tempFile);
                    var outputDocument = converter.Convert(svgDocument).WrappedDocument;
                    PrintWarnings(subpath, converter.Warnings);

                    var outputFile = Path.Combine(options.OutputDirectory, subpath);
                    outputFile = Path.ChangeExtension(outputFile, "xml");
                    outputFile = PathHelper.NormalizeFileName(outputFile);

                    Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
                    var settings = new XmlWriterSettings
                    {
                        Encoding            = new UTF8Encoding(false),
                        Indent              = true,
                        IndentChars         = new string(' ', 4),
                        NewLineOnAttributes = true
                    };
                    using (var writer = XmlWriter.Create(outputFile, settings))
                    {
                        outputDocument.Save(writer);
                    }
                }
                catch (FixFillTypeException e)
                {
                    PrintError($"{subpath}: Failure due to the --fix-fill-type option. {e.InnerException.Message}");
                }
                catch (Exception e)
                {
                    PrintError($"{subpath}: {e.Message}");
                }

                File.Delete(tempFile);
            }
        }
예제 #29
0
 public void PIK_ExportTemplateToJson()
 {
     CommandStart.Start(doc =>
     {
         if (!doc.IsNamedDrawing)
         {
             throw new Exception("Чертеж не сохранен на диске");
         }
         var tData = TemplateManager.LoadFromDb(doc.Database);
         var file  = Path.ChangeExtension(doc.Name, "json");
         tData.ExportToJson(file ?? throw new InvalidOperationException());
         Process.Start(file);
     });
 }
예제 #30
0
        /// <summary>
        /// Returns a <see cref="MapFile"/> for the supplied asset.
        /// </summary>
        public static MapFile LoadMapFile(string assetPath)
        {
            string mapPath  = ConfigurationManager <WorldServerConfiguration> .Config.Map.MapPath;
            string asset    = Path.Combine(mapPath, Path.GetFileName(assetPath));
            string filePath = Path.ChangeExtension(asset, ".nfmap");

            using (var stream = System.IO.File.OpenRead(filePath))
                using (var reader = new BinaryReader(stream))
                {
                    var mapFile = new MapFile();
                    mapFile.Read(reader);
                    return(mapFile);
                }
        }