Copy() public static method

public static Copy ( String sourceFileName, String destFileName ) : void
sourceFileName String
destFileName String
return void
コード例 #1
0
        private async Task CopyConfigFile()
        {
            await Task.Run(() =>
            {
                try
                {
                    string sharedConfigFile = Path.Combine(SscUpdateManager.VersionFolder, GlobalResources.ConfigPath);
                    string curConfigFile    = Path.Combine(Environment.CurrentDirectory, GlobalResources.ConfigPath);

                    bool hasSharedConfig = File.Exists(sharedConfigFile);
                    bool useSharedConfig = Settings.Default.UseUserConfig;

                    Log.Logger.Debug($"has shared config?{hasSharedConfig}, useSharedConfig?{useSharedConfig}");

                    if (hasSharedConfig && useSharedConfig)
                    {
                        Log.Logger.Debug($"【copy config file】:copy {sharedConfigFile} to {curConfigFile}");

                        File.Copy(sharedConfigFile, curConfigFile, true);
                    }
                }
                catch (Exception ex)
                {
                    Log.Logger.Error($"【copy config file exception】:{ex}");
                    Current.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        SscDialog dialog = new SscDialog(Messages.ErrorCopyConfigFile);
                        dialog.ShowDialog();
                        Current.Shutdown();
                    }));
                }
            });
        }
コード例 #2
0
        public void GetAssemblyPath_WithHashInDirectoryName()
        {
            string directoryPath        = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "#HashTestPath");
            string originalAssemblyPath = typeof(ReflectionUtilityTest).Assembly.Location;
            string newAssemblyPath      = Path.Combine(directoryPath, Path.GetFileName(originalAssemblyPath));

            if (Directory.Exists(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }

            Directory.CreateDirectory(directoryPath);
            try
            {
                File.Copy(originalAssemblyPath, newAssemblyPath);
                AppDomainRunner.Run(
                    delegate(object[] args)
                {
                    string directory    = (string)args[0];
                    string assemblyPath = (string)args[1];

                    Assembly assembly = Assembly.LoadFile(assemblyPath);
                    Assert.That(Path.GetDirectoryName(assembly.Location), Is.EqualTo(directory));
                    Assert.That(ReflectionUtility.GetAssemblyDirectory(assembly), Is.EqualTo(directory));
                },
                    directoryPath,
                    newAssemblyPath);
            }
            finally
            {
                Directory.Delete(directoryPath, true);
            }
        }
コード例 #3
0
 /// <summary>
 /// Copies a file from a custom folder, into another custom folder.
 /// </summary>
 public static void Custom(this HUMIO.Data.Copy copyData, string filePath, string newFilePath)
 {
     if (SFile.Exists(filePath))
     {
         SFile.Copy(filePath, newFilePath);
     }
 }
コード例 #4
0
        public void Setup()
        {
            var testRoot = TestContext.CurrentContext.TestDirectory.Split("bin")[0];

            // Create an example JSON log file to check results
            // As a one time setup for all tets in this class/fixture
            IIOHelper           ioHelper   = TestHelper.IOHelper;
            IHostingEnvironment hostingEnv = TestHelper.GetHostingEnvironment();

            ILoggingConfiguration loggingConfiguration = TestHelper.GetLoggingConfiguration(hostingEnv);

            var exampleLogfilePath = Path.Combine(testRoot, "TestHelpers", "Assets", LogfileName);

            _newLogfileDirPath = loggingConfiguration.LogDirectory;
            _newLogfilePath    = Path.Combine(_newLogfileDirPath, LogfileName);

            // Create/ensure Directory exists
            ioHelper.EnsurePathExists(_newLogfileDirPath);

            // Copy the sample files
            File.Copy(exampleLogfilePath, _newLogfilePath, true);

            ILogger <SerilogJsonLogViewer> logger = Mock.Of <ILogger <SerilogJsonLogViewer> >();
            var logViewerConfig = new LogViewerConfig(LogViewerQueryRepository, Mock.Of <IScopeProvider>());
            var logLevelLoader  = Mock.Of <ILogLevelLoader>();

            _logViewer = new SerilogJsonLogViewer(logger, logViewerConfig, loggingConfiguration, logLevelLoader, Log.Logger);
        }
コード例 #5
0
        private void CopyDirectory(string sourceFolder, string destinationFolder)
        {
            // check that source and destination folders exist
            if (!sourceFolder.DirectoryExists() || !destinationFolder.DirectoryExists())
            {
                return;
            }

            // copy the files over
            foreach (var file in Directory.EnumerateFiles(sourceFolder))
            {
                File.Copy(file, Path.Combine(destinationFolder, Path.GetFileName(file)), true);
            }

            // copy the directories over
            foreach (var directory in Directory.EnumerateDirectories(sourceFolder))
            {
                var destinationDirName = Path.Combine(destinationFolder, Path.GetFileName(directory));

                if (!Directory.Exists(destinationDirName))
                {
                    Directory.CreateDirectory(destinationDirName);
                }

                CopyDirectory(directory, destinationDirName);
            }
        }
コード例 #6
0
        private static async Task CopyDirectory(string source, string destination)
        {
            foreach (var dir in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
            {
                Directory.CreateDirectory(dir.Replace(source, destination));
            }

            foreach (var file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
            {
                var attempt       = 0;
                var totalAttempts = 100;
                try
                {
                    File.Copy(file, file.Replace(source, destination), true);
                }
                catch (IOException)
                {
                    if (attempt++ == totalAttempts)
                    {
                        throw;
                    }

                    await Task.Delay(10);
                }
            }
        }
コード例 #7
0
        public async Task <HttpResponseMessage> Upload(string folderName)
        {
            try
            {
                var provider = new MultipartFormDataStreamProvider(AppSettings.WorkingDirectory);
                await Request.Content.ReadAsMultipartAsync(provider);

                Directory.CreateDirectory(Path.Combine(AppSettings.WorkingDirectory, folderName));

                foreach (var file in provider.FileData)
                {
                    var name = file.Headers.ContentDisposition.FileName.Trim('"');
                    var path = Path.Combine(AppSettings.WorkingDirectory, folderName, name);
                    File.Copy(file.LocalFileName, path, true);
                    File.Delete(file.LocalFileName);
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (Exception e)
            {
                NLogger.LogError(App, "Upload", e.Message, folderName);
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, e));
            }
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: KalleHoppe/ImageSorter
        private static void CopyFile(string newDesitnationFolder, string newFullPath, string duplicateDesitnationFolder,
                                     string file)
        {
            //If the dir is missing, create a new and move the file
            if (!Directory.Exists(newDesitnationFolder))
            {
                Directory.CreateDirectory(newDesitnationFolder);
            }

            //Move the file to the corresponding directory
            if (File.Exists(newFullPath))
            {
                newFullPath = duplicateDesitnationFolder + Path.GetFileName(file);
                if (!Directory.Exists(duplicateDesitnationFolder))
                {
                    Directory.CreateDirectory(duplicateDesitnationFolder);
                }
                LogUtility.LogDuplicate("Moved file to " + newFullPath);
            }

            if (!File.Exists(newFullPath))
            {
                File.Copy(file, newFullPath);
                Print("Moved " + file + " ==> " + newFullPath);
                _movedFiles.Add(file);
            }
            else
            {
                Print("File " + newFullPath + " not copied, It already exist in destination and duplicate folder");
            }
        }
コード例 #9
0
        public void SetUp()
        {
            var path = Path.Combine(TestContext.CurrentContext.TestDirectory, "files", "LOFT_ECSS-E-TM-10-25_AnnexC.zip");
            var migrationSourceFile = Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\files", "migration.json");

            this.annexC3File   = Path.Combine(TestContext.CurrentContext.TestDirectory, "files", "AnnexC3.zip");
            this.migrationFile = Path.Combine(TestContext.CurrentContext.TestDirectory, "files", "migration.json");

            if (!File.Exists(this.migrationFile))
            {
                File.Copy(migrationSourceFile, this.migrationFile);
            }

            this.cancelationTokenSource = new CancellationTokenSource();
            this.credentials            = new Credentials("admin", "pass", new Uri(path));
            this.session = new Mock <ISession>();

            this.dal = new JsonFileDal
            {
                Session = this.session.Object
            };

            this.siteDirectoryData = new SiteDirectory();
            this.session.Setup(x => x.RetrieveSiteDirectory()).Returns(this.siteDirectoryData);
            this.session.Setup(x => x.Credentials).Returns(this.credentials);
        }
コード例 #10
0
        private static IList <string> GetAndCopyPostProcessScripts(TestBench selectedTestBench, string projectDirectory, string outputDirectory)
        {
            var scripts = new List <string>();

            foreach (var postprocessItem in selectedTestBench.Children.PostProcessingCollection)
            {
                if (postprocessItem.Attributes.ScriptPath != "")
                {
                    var fileNameOnly = Path.GetFileName(postprocessItem.Attributes.ScriptPath);

                    if (fileNameOnly != null)
                    {
                        if (File.Exists(Path.Combine(outputDirectory, fileNameOnly)))
                        {
                            GMEConsole.Warning.WriteLine(
                                "PostProcessing script {0} already exists in output directory", fileNameOnly);
                        }
                        else
                        {
                            File.Copy(Path.Combine(projectDirectory, postprocessItem.Attributes.ScriptPath), Path.Combine(outputDirectory, fileNameOnly));
                            scripts.Add(fileNameOnly);
                        }
                    }
                }
            }

            return(scripts);
        }
コード例 #11
0
 /// <summary>
 /// 备份xml文件
 /// </summary>
 public void Backup()
 {
     if (XmlDefined)
     {
         File.Copy(XmlFileLocation, BakFileLocation, true);
     }
 }
コード例 #12
0
ファイル: File.cs プロジェクト: devsia93/file-manager-library
        public void delete(bool Copy)
        {
            if (SFile.Exists(fname) & fname.Length <= 260)//проверка на существование файла и корректность имени
            {
                try
                {
                    if (!Copy)
                    {
                        stream.Close();      //закрываем поток
                        SFile.Delete(fname); //удаляем файл
                        fname = null;        //обнуляем путь
                        stream.Flush();      //очищаем буфер потока
                    }
                    else
                    {
                        stream.Close();
                        SFile.Copy(fname, @"C:\\FileManagerLog\Temp");
                        SFile.Delete(fname); //удаляем файл
                        fname = null;        //обнуляем путь
                        stream.Flush();      //очищаем буфер потока
                    }
                }

                catch (Exception e) //обработка исключений для удаления
                {
                    throw e;
                }
            }
            else
            {
                LogForOperations("Удаление файла", "файла не существует");//запись в лог ошибки (если есть)
            }
        }
コード例 #13
0
 /// <summary>
 /// Copy the given repository file to a temporary file and open it.
 /// </summary>
 /// <param name="repositoryFilePath"></param>
 public TemporaryFileBasedRepository(string repositoryFilePath)
 {
     Console.Write("Creating temporary file-based repository: \"{0}\" ... ", TempFileName);
     File.Copy(repositoryFilePath, TempFileName, true);
     repo.OpenFile(TempFileName);
     Console.WriteLine("done");
 }
コード例 #14
0
 public FileController(WebSocket client, Packets packet)
 {
     _client = client;
     _packet = packet;
     //only do this operation on search request
     if (_packet.PacketType == PacketType.SearchFiles)
     {
         var startupDirEndingWithSlash = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) +
                                         "\\";
         var resolvedDomainTimeFileName = startupDirEndingWithSlash + "Everything.dll";
         if (!File.Exists(resolvedDomainTimeFileName))
         {
             if (IntPtr.Size == 8)
             {
                 Console.WriteLine(@"x64 Everything Loaded");
                 if (File.Exists(startupDirEndingWithSlash + "Everything64.dll"))
                 {
                     File.Copy(startupDirEndingWithSlash + "Everything64.dll", resolvedDomainTimeFileName);
                 }
             }
             else
             {
                 Console.WriteLine(@"x86 Everything Loaded");
                 if (File.Exists(startupDirEndingWithSlash + "Everything32.dll"))
                 {
                     File.Copy(startupDirEndingWithSlash + "Everything32.dll", resolvedDomainTimeFileName);
                 }
             }
         }
     }
 }
コード例 #15
0
        private void Create(Configuration configuration)
        {
            var settings           = configuration.AppSettings.Settings;
            var baseDirectory      = AppDomain.CurrentDomain.BaseDirectory;
            var applicationPathKey = "applicationPath";

            if (!settings.AllKeys.Contains(applicationPathKey))
            {
                throw new Exception("请配置应用程序路径");
            }

            var applicationPath = Path.Combine(baseDirectory, settings["applicationPath"].Value);
            var applicationConfigurationPath = applicationPath + ConfigurationExt;
            // 复制应用程序并改名
            var applicationName      = settings["applicationName"].Value;
            var exeName              = applicationName + Path.GetExtension(applicationPath);
            var exePath              = Path.Combine(baseDirectory, exeName);
            var exeConfigurationName = exeName + ConfigurationExt;
            var exeConfigurationPath = Path.Combine(baseDirectory, exeConfigurationName);

            File.Copy(applicationPath, exePath, true);
            File.Copy(applicationConfigurationPath, exeConfigurationPath, true);
            // 生存快捷方式
            var description      = settings["description"].Value;
            var desktopDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            var shortcutPath     = Path.Combine(desktopDirectory, $"{applicationName}.lnk");
            var shell            = new WshShell();
            var shortcut         = (IWshShortcut)shell.CreateShortcut(shortcutPath);

            shortcut.TargetPath       = exePath;
            shortcut.WorkingDirectory = Path.GetDirectoryName(exePath);
            shortcut.WindowStyle      = 1;
            shortcut.Description      = description;
            shortcut.Save();
        }
コード例 #16
0
        private void ConfigureSearch()
        {
            var startupDirEndingWithSlash = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) +
                                            "\\";
            var resolvedDomainTimeFileName = startupDirEndingWithSlash + "Everything.dll";

            if (!File.Exists(resolvedDomainTimeFileName))
            {
                if (IntPtr.Size == 8)
                {
                    Console.WriteLine(@"x64 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything64.dll"))
                    {
                        File.Copy(startupDirEndingWithSlash + "Everything64.dll", resolvedDomainTimeFileName);
                    }
                }
                else
                {
                    Console.WriteLine(@"x86 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything32.dll"))
                    {
                        File.Copy(startupDirEndingWithSlash + "Everything32.dll", resolvedDomainTimeFileName);
                    }
                }
            }
        }
コード例 #17
0
ファイル: BootUtils.cs プロジェクト: xydoublez/SocketUpdater
 /// <summary>
 /// Create lnk for Restart.vbs in Startup Folder
 /// </summary>
 /// <param name="lnkNameWithoutExt"></param>
 /// <param name="lnkTempDirPath">Some dirs can't create lnk!</param>
 /// <param name="vbScriptPath">path must with extenstion!</param>
 /// <returns></returns>
 public static bool CreateLnk(string lnkNameWithoutExt, string lnkTempDirPath, string vbScriptPath)
 {
     if (string.IsNullOrEmpty(lnkNameWithoutExt) || string.IsNullOrEmpty(lnkTempDirPath) ||
         string.IsNullOrEmpty(vbScriptPath))
     {
         return(false);
     }
     if (!Directory.Exists(lnkTempDirPath))
     {
         Directory.CreateDirectory(lnkTempDirPath);
     }
     try
     {
         if (!File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.Startup) + $"\\{lnkNameWithoutExt}.lnk"))
         {
             var shell    = new WshShell();
             var shortcut = (IWshShortcut)shell.CreateShortcut(Path.Combine(lnkTempDirPath, $"{lnkNameWithoutExt}.lnk"));
             shortcut.WorkingDirectory = Path.GetDirectoryName(vbScriptPath);
             shortcut.TargetPath       = vbScriptPath;
             shortcut.WindowStyle      = 7;
             shortcut.Save();
             var sourcePath = Path.Combine(lnkTempDirPath, $"{lnkNameWithoutExt}.lnk");
             var destPath   = Environment.GetFolderPath(Environment.SpecialFolder.Startup) + $"\\{lnkNameWithoutExt}.lnk";
             File.Copy(sourcePath, destPath);
             return(File.Exists(destPath));
         }
     }
     catch
     {
         return(false);
     }
     return(false);
 }
コード例 #18
0
 static void SortByAlbum(KeyValuePair <AudioFile, String> audioFile)
 {
     try
     {
         sortType = "album";
         if (audioFile.Key.Tag.Album == "Unknown Album")
         {
             Directory.CreateDirectory(pathOutput + @"\" + audioFile.Key.Tag.Album.Replace(":", " -") + @"\" + audioFile.Key.Tag.AlbumArtists[0]);
             File.Copy(audioFile.Key.Name,
                       pathOutput + @"\" + audioFile.Key.Tag.Album.Replace(":", " -") + @"\" + audioFile.Key.Tag.AlbumArtists[0] + @"\" + audioFile.Value);
         }
         else
         {
             Directory.CreateDirectory(pathOutput + @"\" + audioFile.Key.Tag.Album.Replace(":", " -"));
             File.Copy(audioFile.Key.Name,
                       pathOutput + @"\" + audioFile.Key.Tag.Album.Replace(":", " -") + @"\" + audioFile.Value);
         }
     }
     catch (DirectoryNotFoundException)
     {
         Console.WriteLine("Unable to find file (" + audioFile.Key.Name + ")!");
     }
     catch (Exception)
     {
         Console.WriteLine("An occured error with file (" + audioFile.Key.Name + ")!");
     }
 }
コード例 #19
0
        private static void AppendFileXml(FileInfo file, string filePath, string packageDirectory, XContainer filesXml)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }
            if (string.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(filePath));
            }
            if (string.IsNullOrWhiteSpace(packageDirectory))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(packageDirectory));
            }

            var orgPath     = filePath.Substring(0, (filePath.LastIndexOf('/')));
            var orgName     = filePath.Substring((filePath.LastIndexOf('/') + 1));
            var newFileName = orgName;

            if (File.Exists(packageDirectory.EnsureEndsWith('/') + orgName))
            {
                newFileName = Guid.NewGuid() + "_" + newFileName;
            }

            //Copy file to directory for zipping...
            File.Copy(file.FullName, packageDirectory + "/" + newFileName, true);

            filesXml.Add(new XElement("file",
                                      new XElement("guid", newFileName),
                                      new XElement("orgPath", orgPath == "" ? "/" : orgPath),
                                      new XElement("orgName", orgName)));
        }
コード例 #20
0
        public virtual int AddCourse(Course course)
        {
            course.Created   = DateTime.Now;
            course.Updated   = DateTime.Now;
            course.UpdatedBy = course.Owner;
            var db = this.GetDbContext();

            db.Courses.InsertOnSubmit(course);
            db.SubmitChanges();

            var path = this.GetCoursePath(course.Id);

            @Directory.CreateDirectory(path);

            var templatePath = this.GetTemplatesPath();

            foreach (var templateFile in this.templateFiles)
            {
                File.Copy(Path.Combine(templatePath, templateFile), Path.Combine(path, templateFile), true);
            }

            this.LmsService.Inform(CourseNotifications.CourseCreate, course);

            return(course.Id);
        }
コード例 #21
0
        public void FileCreationAndPreservation()
        {
            string inputFileName = "fileCreationAndPreservation.wav";
            string inputFilePath = Path.Combine(Environment.CurrentDirectory, inputFileName);

            if (!File.Exists(inputFilePath))
            {
                File.Copy(TestConstant.SourceFilePath16Bit, inputFilePath);
            }

            CrossTimeEngine engine         = new CrossTimeEngine(TestConstant.DefaultConfigurationFile, this);
            string          outputFileName = String.Format("{0}{1}.wav", Path.GetFileNameWithoutExtension(inputFilePath), engine.Configuration.Output.CollidingFileNamePostfix);

            this.RemoveExistingOutputFiles(outputFileName);
            DateTime startUtc = DateTime.UtcNow;

            // process file and output file should be created
            engine.Configuration.Filters.Clear();
            engine.FilterFiles(Environment.CurrentDirectory, inputFileName, Environment.CurrentDirectory);
            DateTime firstOutputFileWriteTimeUtc = File.GetLastWriteTimeUtc(outputFileName);

            Assert.IsTrue(firstOutputFileWriteTimeUtc > startUtc);

            // since no filters are configured the output file should be a clone of the input
            this.VerifyWaveFilesEquivalent(outputFileName, inputFileName, 1.0, 0.0, true);

            // filter again and the output file should not be touched
            engine.FilterFiles(Environment.CurrentDirectory, inputFileName, Environment.CurrentDirectory);
            DateTime secondOutputFileWriteTimeUtc = File.GetLastWriteTimeUtc(outputFileName);

            Assert.AreEqual(firstOutputFileWriteTimeUtc, secondOutputFileWriteTimeUtc, "Output file {0} was touched after initial write at {1} by second write at {2}.", inputFilePath, firstOutputFileWriteTimeUtc, secondOutputFileWriteTimeUtc);
        }
コード例 #22
0
        public virtual int?AddNode(Node node)
        {
            var db = this.GetDbContext();

            if (node.Sequencing == null)
            {
                var xs = new XmlSerializer(typeof(Sequencing));
                node.Sequencing = xs.SerializeToXElemet(new Sequencing());
            }

            db.Nodes.InsertOnSubmit(node);
            db.SubmitChanges();

            if (!node.IsFolder)
            {
                var template = Path.Combine(this.GetTemplatesPath(), "iudico.html");

                File.Copy(template, this.GetNodePath(node.Id) + ".html", true);
            }

            this.LmsService.Inform(CourseNotifications.NodeCreate, node);

            var course = node.Course;

            this.UpdateCourse(course.Id, course);

            return(node.Id);
        }
コード例 #23
0
        /// <summary>
        /// Check that the dataset built using the DataSetBuilder with default caches
        /// contains the same data as that built using the MemoryFactory
        /// </summary>
        public void DataSetBuilder_Compare()
        {
            // Arange
            string tempFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".tmp");

            File.Copy(DataFile, tempFile);

            try
            {
                // Act
                using (IndirectDataSet fileDataset =
                           BuildDataset(
                               InitBuilder()
                               .ConfigureDefaultCaches()))
                {
                    using (DataSet memoryDataset = MemoryFactory.Create(tempFile))
                    {
                        // Assert
                        Assert.IsTrue(Utils.CompareDataSets(fileDataset, memoryDataset),
                                      "Data loaded by DataSetBuilder does not match that loaded by MemoryFactory from the same file");
                    }
                }
            }
            finally
            {
                // tidy up
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
コード例 #24
0
        private void Startup()
        {
            string path  = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RemotePresentationManager");
            string exe   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RemotePresentationManager", "RemotePresentationManager.exe");
            string token = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RemotePresentationManager", "token.txt");
            string lnk   = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Windows\Start Menu\Programs\Startup\RPM.lnk");

            Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RemotePresentationManager"));
            if (File.Exists(exe))
            {
                File.Delete(exe);
            }
            File.Copy(Application.ExecutablePath, exe);
            if (File.Exists(token))
            {
                File.Delete(token);
            }
            File.Copy("token.txt", token);
            //File.WriteAllText(bat, String.Format("start {0} {1}", exe, "WEBONLY"));
            WshShell     shell    = new WshShell();
            IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(lnk);

            shortcut.Description      = "r/programmerhumor";
            shortcut.TargetPath       = exe;
            shortcut.Arguments        = "WEBONLY";
            shortcut.WorkingDirectory = path;
            shortcut.Save();
        }
コード例 #25
0
        protected void ProcessResource(Node node, Resource resource)
        {
            var nodePath   = this.courseStorage.GetNodePath(node.Id);
            var coursePath = this.courseStorage.GetCoursePath(node.CourseId);

            File.Copy(Path.Combine(this.courseTempPath, resource.Href), nodePath + ".html", true);

            foreach (var file in resource.Files)
            {
                if (file.Href != resource.Href)
                {
                    var path = Path.Combine(coursePath, file.Href);
                    if (!Directory.GetParent(path).Exists)
                    {
                        Directory.CreateDirectory(Directory.GetParent(path).ToString());
                    }

                    File.Copy(Path.Combine(this.courseTempPath, file.Href), Path.Combine(coursePath, file.Href));
                }
            }

            foreach (var dependency in resource.Dependencies)
            {
                var depResource = this.manifest.Resources.ResourcesList.Where(r => r.Identifier == dependency.IdentifierRef).FirstOrDefault();

                if (depResource != null)
                {
                    this.manifest.Resources.ResourcesList.Remove(depResource);

                    this.ProcessDependencyResource(node, depResource);
                }
            }
        }
コード例 #26
0
        public FileResult DynamicApplication()
        {
            var  stampText          = $"Server time is currently {DateTime.Now} at time of stamping";
            var  stampData          = Encoding.UTF8.GetBytes(stampText);
            var  sourceFile         = Server.MapPath("~/Content/Demo Application.exe");
            var  signToolPath       = Server.MapPath("~/App_Data/signtool.exe");
            var  tempFile           = Path.GetTempFileName();
            bool deleteStreamOpened = false;

            try
            {
                IOFile.Copy(sourceFile, tempFile, true);
                StampWriter.StampFile(tempFile, signToolPath, StampConstants.StampSubject, StampConstants.StampOid, stampData);

                var deleteOnClose = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 4096, FileOptions.DeleteOnClose);
                deleteStreamOpened = true;
                return(File(deleteOnClose, "application/octet-stream", "Demo Application.exe"));
            }
            finally
            {
                if (!deleteStreamOpened)
                {
                    try
                    {
                        IOFile.Delete(tempFile);
                    }
                    catch
                    {
                        // no-op, opportunistic cleanup
                        Debug.WriteLine("Failed to cleanup file");
                    }
                }
            }
        }
コード例 #27
0
        protected void ProcessResource(Node node, Resource resource)
        {
            var nodePath   = _CourseStorage.GetNodePath(node.Id);
            var coursePath = _CourseStorage.GetCoursePath(node.CourseId);

            File.Copy(Path.Combine(_CourseTempPath, resource.Href), nodePath + ".html", true);

            foreach (var file in resource.Files)
            {
                if (file.Href != resource.Href)
                {
                    File.Copy(Path.Combine(_CourseTempPath, file.Href), Path.Combine(coursePath, file.Href));
                }
            }

            foreach (var dependency in resource.Dependencies)
            {
                var depResource = _Manifest.Resources._Resources.Where(r => r.Identifier == dependency.IdentifierRef).FirstOrDefault();

                if (depResource != null)
                {
                    _Manifest.Resources._Resources.Remove(depResource);

                    ProcessDependencyResource(node, depResource);
                }
            }
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: UNDEFINED-BEHAVIOR/rbfx
        private string VersionFile(string path)
        {
            if (path == null)
            {
                throw new ArgumentException($"{nameof(path)} may not be null.");
            }

            var pdbPath       = Path.ChangeExtension(path, "pdb");
            var versionedPath = GetNewPluginPath(path);

            Directory.CreateDirectory(Path.GetDirectoryName(versionedPath));
            Debug.Assert(versionedPath != null, $"{nameof(versionedPath)} != null");
            File.Copy(path, versionedPath, true);

            if (File.Exists(pdbPath))
            {
                var versionedPdbPath = Path.ChangeExtension(versionedPath, "pdb");
                File.Copy(pdbPath, versionedPdbPath, true);
                versionedPdbPath = Path.GetFileName(versionedPdbPath);  // Do not include full path when patching dll

                // Update .pdb path in a newly copied file
                var pathBytes = Encoding.ASCII.GetBytes(Path.GetFileName(pdbPath)); // Does this work with i18n paths?
                var dllBytes  = File.ReadAllBytes(versionedPath);
                int i;
                for (i = 0; i < dllBytes.Length; i++)
                {
                    if (dllBytes.Skip(i).Take(pathBytes.Length).SequenceEqual(pathBytes)) // I know its slow ¯\_(ツ)_/¯
                    {
                        if (dllBytes[i + pathBytes.Length] != 0)                          // Check for null terminator
                        {
                            continue;
                        }

                        while (dllBytes[--i] != 0)
                        {
                            // We found just a file name. Time to walk back to find a start of the string. This is
                            // required because dll is executing from non-original directory and pdb path points
                            // somewhere else we can not predict.
                        }

                        i++;

                        // Copy full pdb path
                        var newPathBytes = Encoding.ASCII.GetBytes(versionedPdbPath);
                        newPathBytes.CopyTo(dllBytes, i);
                        dllBytes[i + newPathBytes.Length] = 0;
                        break;
                    }
                }

                if (i == dllBytes.Length)
                {
                    return(null);
                }

                File.WriteAllBytes(versionedPath, dllBytes);
            }

            return(versionedPath);
        }
コード例 #29
0
        private void InstallProgram(string path)
        {
            Logger.Info($"Installing SRS Program to {path}");
            _progressBarDialog.UpdateProgress(false, $"Installing SRS at {path}");
            //sleep! WTF directory is lagging behind state here...
            Task.Delay(TimeSpan.FromMilliseconds(200)).Wait();

            _progressBarDialog.UpdateProgress(false, $"Creating Directories at {path}");

            Logger.Info($"Creating Directories");
            CreateDirectory(path);
            CreateDirectory(path + "\\AudioEffects");
            CreateDirectory(path + "\\Scripts");

            //sleep! WTF directory is lagging behind state here...
            Task.Delay(TimeSpan.FromMilliseconds(200)).Wait();
            _progressBarDialog.UpdateProgress(false, $"Copying Program Files at {path}");

            Logger.Info($"Copying binaries");
            File.Copy(_currentDirectory + "\\opus.dll", path + "\\opus.dll", true);
            File.Copy(_currentDirectory + "\\speexdsp.dll", path + "\\speexdsp.dll", true);
            File.Copy(_currentDirectory + "\\awacs-radios.json", path + "\\awacs-radios.json", true);

            File.Copy(_currentDirectory + "\\SR-ClientRadio.exe", path + "\\SR-ClientRadio.exe", true);
            File.Copy(_currentDirectory + "\\SR-Server.exe", path + "\\SR-Server.exe", true);
            File.Copy(_currentDirectory + "\\SRS-AutoUpdater.exe", path + "\\SRS-AutoUpdater.exe", true);
            File.Copy(_currentDirectory + "\\DCS-SR-ExternalAudio.exe", path + "\\DCS-SR-ExternalAudio.exe", true);
            File.Copy(_currentDirectory + "\\grpc_csharp_ext.x64.dll", path + "\\grpc_csharp_ext.x64.dll", true);

            Logger.Info($"Copying directories");
            DirectoryCopy(_currentDirectory + "\\AudioEffects", path + "\\AudioEffects");
            DirectoryCopy(_currentDirectory + "\\Scripts", path + "\\Scripts");

            Logger.Info($"Finished installing SRS Program to {path}");
        }
コード例 #30
0
        public int?AddNode(Node node)
        {
            using (var db = new CourseManagementDbConext())
            {
                if (node.Sequencing == null)
                {
                    var sw = new StringWriter();
                    var xs = new XmlSerializer(typeof(Sequencing));
                    xs.Serialize(sw, new Sequencing());
                    node.Sequencing = sw.ToString();
                }

                db.Nodes.Add(node);
                db.SaveChanges();

                if (!node.IsFolder)
                {
                    var template = Path.Combine(GetTemplatesPath(), "iudico.html");

                    File.Copy(template, GetNodePath(node.Id) + ".html", true);
                }

                return(node.Id);
            }
        }