MoveTo() private method

private MoveTo ( String destFileName ) : void
destFileName String
return void
Example #1
3
 public static void Log(string entry)
 {
     if (console_mode)
     {
         Console.WriteLine(entry);
     }
     StreamWriter writer = null;
     try
     {
         FileInfo info = new FileInfo(fileName);
         if (info.Exists && (info.Length >= 0x100000))
         {
             string path = fileName + ".old";
             File.Delete(path);
             info.MoveTo(path);
         }
         writer = new StreamWriter(fileName, true);
         writer.WriteLine("[{0:yyyy-MM-dd HH:mm:ss}] {1}", DateTime.Now, entry);
         writer.Flush();
     }
     catch (Exception)
     {
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
         }
     }
 }
        /// <summary>
        /// Archives the exception report.
        /// The name of the PDF file is modified to make it easier to identify.
        /// </summary>
        /// <param name="pdfFile">The PDF file.</param>
        /// <param name="archiveDirectory">The archive directory.</param>
        public static void ArchiveException(FileInfo pdfFile, string archiveDirectory)
        {
            // Create a new subdirectory in the archive directory
            // This is based on the date of the report being archived
            DirectoryInfo di = new DirectoryInfo(archiveDirectory);
            string archiveFileName = pdfFile.Name;
            string newSubFolder = ParseFolderName(archiveFileName);
            try
            {
                di.CreateSubdirectory(newSubFolder);
            }
            catch (Exception ex)
            {
                // The folder already exists so don't create it
            }

            // Create destination path
            // Insert _EXCEPT into file name
            // This will make it easier to identify as an exception in the archive folder
            string destFileName = archiveFileName.Insert(archiveFileName.IndexOf("."), "_EXCEPT");
            string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + destFileName;

            // Move the file to the archive directory
            try
            {
                pdfFile.MoveTo(destFullPath);
            }
            catch (Exception ex)
            {
            }
        }
        public void Execute()
        {
            var files = Directory.GetFiles(SourceFolder, "*.jpg");
            foreach (var file in files)
            {
                try
                {
                    DateTime dt;
                    using (var em = new ExifManager(file))
                    {
                        dt = em.DateTimeOriginal;
                    }

                    if (dt == DateTime.MinValue) continue;

                    var fi = new FileInfo(file);
                    var newName = Path.Combine(DestinantionFolder,
                                               string.Format("{0}.jpg", dt.ToString("yyyy-MM-dd_HH.mm.ss")));
                    fi.MoveTo(newName);
                }
                catch
                {
                }
            }

        }
Example #4
0
    /// <summary>
    /// 檔案重新命名(傳入虛擬路徑)
    /// </summary>
    /// <param name="srcFile">原始路徑(虛擬路徑)</param>
    /// <param name="dstFile">目的路徑(虛擬路徑)</param>
    /// <param name="backupFlag">檔案衝突時是否備份舊檔</param>
    public static void RenameFile(string srcFile, string dstFile, bool backupFlag)
    {
        System.IO.FileInfo sFi         = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(srcFile));
        System.IO.FileInfo dFi         = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(dstFile));
        string             backup_name = String.Format("{0}_{1}-{2}{3}"
                                                       , Path.GetFileNameWithoutExtension(dFi.Name)
                                                       , DateTime.Now.ToString("yyyyMMddHHmmss")
                                                       , Sys.GetSession("scode")
                                                       , dFi.Extension);

        if (HttpContext.Current.Request["chkTest"] != "TEST")
        {
            //來源跟目的不同時才要搬,否則會出錯
            if (sFi.FullName.ToLower() != dFi.FullName.ToLower())
            {
                if (dFi.Exists && backupFlag)  //檔案有衝突,備份原檔
                {
                    dFi.CopyTo(dFi.DirectoryName + "\\" + backup_name, true);
                    sFi.CopyTo(dFi.FullName, true);
                    sFi.Delete();
                }
                else if (dFi.Exists && !backupFlag)    //檔案有衝突,直接覆蓋
                {
                    dFi.Delete();
                    sFi.MoveTo(dFi.FullName);
                }
                else
                {
                    sFi.MoveTo(dFi.FullName);
                }
            }
        }
        else
        {
            HttpContext.Current.Response.Write("來源=" + sFi.FullName + "<BR>");
            HttpContext.Current.Response.Write("目的=" + dFi.FullName + "<BR>");
            if (sFi.FullName.ToLower() != dFi.FullName.ToLower())
            {
                HttpContext.Current.Response.Write("衝突備份=" + dFi.DirectoryName + "\\" + backup_name + "<HR>");
            }
            //來源跟目的不同時才要搬,否則會出錯
            //測試模式不搬動.只複製檔案
            if (sFi.FullName.ToLower() != dFi.FullName.ToLower())
            {
                if (dFi.Exists)
                {
                    dFi.CopyTo(dFi.DirectoryName + "\\" + backup_name, true);
                    sFi.CopyTo(dFi.FullName, true);
                }
                else
                {
                    sFi.CopyTo(dFi.FullName);
                }
            }
        }
    }
        public async Task<HttpResponseMessage> Upload()//int clientSurveyId
        {
            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
            }

            string root = Classes.Utility.ImagesFolder; //System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
            //validate if the upload folder exists. If not, create one
            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);
                List<string> newFiles = new List<string>();
                int clientSurveyId =0;
                // Save each images files separately instead of a single multipart file
                foreach (MultipartFileData file in provider.FileData)
                {
                    //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    //Trace.WriteLine("Server file path: " + file.LocalFileName);
                    string fileName = file.Headers.ContentDisposition.FileName;
                    var newName = fileName;
                    var fullName = string.Empty;
                    var newFile = new FileInfo(file.LocalFileName);

                    if (fileName.Contains("\""))
                        newName =  fileName.Substring(1, fileName.Length - 2);

                    fullName = Path.Combine(root.ToString(), newName);

                    newFile.MoveTo(fullName);
                    // get id from the first file
                    if (clientSurveyId == 0)
                    {
                        clientSurveyId = GetId(newName);
                    }
                    if (clientSurveyId>0)
                    {
                        Image image = new Image() { ClientId = 1, path = fileName, ClientSurveyId = clientSurveyId }; 
                        db.Images.Add(image);
                        newFiles.Add(newName);
                    }
                }
                //save image file name to image table in the database
                db.SaveChanges();
                return Request.CreateResponse(HttpStatusCode.OK, newFiles.Count + " file(s) uploaded.");
            }
            catch (System.Exception e)
            {
                CommonLib.ExceptionUtility.LogException(CommonLib.ExceptionUtility.Application.General, e, "Post Images");
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
Example #6
0
        public PluginFileManager( Guid abcPluginGuid, PluginType abcPluginType, string pluginPath = null )
        {
            // Plug-in paths setup.
            _pluginDownloadPath = RemotePluginPath + abcPluginGuid + PluginExtention;
            _pluginTempPath = Path.Combine( GetPluginDirectory( abcPluginType ), TempDirectory, abcPluginGuid.ToString() ) + GetPluginExtention( abcPluginType );
            _pluginPath = pluginPath ?? Path.Combine( GetPluginDirectory( abcPluginType ), abcPluginGuid.ToString() ) + GetPluginExtention( abcPluginType );

            _pluginfileInfo = new FileInfo( _pluginTempPath );

            if ( !Directory.Exists( _pluginTempPath ) )
            {
                Directory.CreateDirectory( _pluginfileInfo.DirectoryName );
            }

            _webClient = new WebClient();
            _webClient.DownloadFileCompleted += ( sender, args ) =>
            {
                // When download is completed and performed properly move to final destination, otherwise delete.
                if ( args.Error == null && !args.Cancelled )
                {
                    _pluginfileInfo.MoveTo( Path.Combine( _pluginfileInfo.Directory.Parent.FullName, _pluginfileInfo.Name ) );
                }
                else
                {
                    File.Delete( _pluginTempPath );
                }
            };
        }
Example #7
0
        private static void MoveFileTo(FileInfo srcFileInfo, String destDir)
        {
            string createDate = srcFileInfo.LastWriteTime.ToString("yyyyMM");
            string ext = srcFileInfo.Extension;
            string imagesExt = "jpg|jpeg|png";
            string vedioExt = "mp4|3gp";

            string path = destDir + @"\";
            if (Regex.IsMatch(ext, imagesExt, RegexOptions.IgnoreCase))
            {
                path += @"照片\" + createDate + @"\";
            }
            else if (Regex.IsMatch(ext, vedioExt, RegexOptions.IgnoreCase))
            {
                path += @"视频\" + createDate + @"\";
            }
            else
            {
                path += @"其他\" + createDate + @"\";
            }

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

            srcFileInfo.MoveTo(path + srcFileInfo.Name);
        }
Example #8
0
        private static void MigrateLegacyDictionaries()
        {
            var oldNewDictionaryFileNames = new List<Tuple<string, string>>
            {
                new Tuple<string, string>("AmericanEnglish.dic", "EnglishUS.dic"),
                new Tuple<string, string>("BritishEnglish.dic", "EnglishUK.dic"),
                new Tuple<string, string>("CanadianEnglish.dic", "EnglishCanada.dic"),
            };

            foreach (var oldNewFileName in oldNewDictionaryFileNames)
            {
                var oldDictionaryPath = GetUserDictionaryPath(oldNewFileName.Item1);
                var oldFileInfo = new FileInfo(oldDictionaryPath);
                var newDictionaryPath = GetUserDictionaryPath(oldNewFileName.Item2);
                var newFileInfo = new FileInfo(newDictionaryPath);
                if (oldFileInfo.Exists)
                {
                    Log.InfoFormat("Old user dictionary file found at '{0}'", oldDictionaryPath);

                    //Delete new user dictionary
                    if (newFileInfo.Exists)
                    {
                        Log.InfoFormat("New user dictionary file also found at '{0}' - deleting this file", newDictionaryPath);
                        newFileInfo.Delete();
                    }

                    //Rename old user dictionary
                    Log.InfoFormat("Renaming old user dictionary file '{0}' to '{1}'", oldDictionaryPath, newDictionaryPath);
                    oldFileInfo.MoveTo(newDictionaryPath);
                }
            }
        }
Example #9
0
        // Moves file from source path to destination
        // path. If it is less than 24 hours old
        // Returns Number of Files Transfered.
        public int moveFiles(string source, string destination)
        {
            int counter = 0;
            source = Path.GetFullPath(source);
            destination = Path.GetFullPath(destination);
            if (Directory.Exists(source))
            {
                string[] files = Directory.GetFiles(source);
                foreach(string s in files)
                {

                    string fileName = (s);
                    FileInfo filePath = new FileInfo(fileName);
                    if (isNewFile(fileName))
                    {
                        string destinationFile = Path.Combine(destination, (Path.GetFileName(fileName)));
                        if (File.Exists(destinationFile))
                        {
                            File.Delete(destinationFile);
                            destinationFile = Path.Combine(destination, (Path.GetFileName(fileName)));
                        }

                        filePath.MoveTo(destinationFile);
                        counter++;
                    }
                }
            }
            return counter;
        }
 public static string RenameFileOrDirectory(string filePath, string newFileName, out bool result)
 {
     result = false;
     if (Directory.Exists(filePath))
     {
         DirectoryInfo di      = new DirectoryInfo(filePath);
         var           newPath = Path.Combine(di.Parent.FullName, newFileName);
         if (!Directory.Exists(newPath))
         {
             di.MoveTo(newPath);
             result = true;
         }
         return(newPath);
     }
     else
     {
         string extensName = Path.GetExtension(filePath);
         string newName    = newFileName + extensName;
         var    newPath    = Path.Combine(Directory.GetParent(filePath).FullName, newName);
         if (!File.Exists(newPath))
         {
             System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
             fi.MoveTo(newPath);
             result = true;
         }
         return(newPath);
     }
 }
Example #11
0
 public static void DoWork(string fullName, bool lookup)
 {
     SourceFile src = new SourceFile(fullName, lookup);
     NewFile nf = new NewFile();
     nf.LoadInfo(src);
     if (src.Series != null && src.Episode != null && !lookup)
     {
         string strEpisode = (src.Episode.Episode < 10) ? "0" + src.Episode.Episode.ToString() : src.Episode.Episode.ToString();
         string strSeason = src.Episode.Season.ToString();
         if (MessageBox.Show(string.Format("Old name: '{0}'\nNew name: '{1} - {2}{3} - {4}'\nIs this correct?", fullName, src.Series.Name, strSeason, strEpisode, src.Episode.Name), "Found a match!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             FileInfo oldFile = new FileInfo(fullName);
             while (true)
             {
                 Rename rn = new Rename(string.Format(@"{0} - {1}{2} - {3}", src.Series.Name, strSeason, strEpisode, src.Episode.Name));
                 DialogResult res = rn.ShowDialog();
                 if (res == DialogResult.OK)
                 {
                     if (File.Exists(oldFile.DirectoryName + "\\" + rn.NewFile + oldFile.Extension))
                     {
                         if (MessageBox.Show(string.Format("The file: {0} already exists! Try another name.", rn.NewFile), "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error) == DialogResult.Cancel)
                             break;
                     }
                     else
                     {
                         string newName = oldFile.DirectoryName + "\\" + rn.NewFile + oldFile.Extension;
                         if (File.Exists(oldFile.FullName))
                         {
                             int count = 0;
                             while (true)
                             {
                                 try
                                 {
                                     oldFile.MoveTo(newName);
                                     break;
                                 }
                                 catch
                                 {
                                     Thread.Sleep(1000);
                                     count++;
                                     if (count == 60)
                                     {
                                         MessageBox.Show(string.Format("File cannot be moved after {0} attempts! Program will now terminate.", count), "File cannot be moved!", MessageBoxButtons.OK);
                                         break;
                                     }
                                 }
                             }
                         }
                         else
                             MessageBox.Show("Original file cannot be found! Program will now terminate.", "File not found!", MessageBoxButtons.OK);
                         return;
                     }
                 }
                 else if (res == DialogResult.Cancel)
                     break;
             }
         }
     }
     nf.ShowDialog();
 }
Example #12
0
 static void MoveToNextAvailableFilename(FileInfo file, string directory, string filename, string extension)
 {
     var newFullName = Path.Combine(directory, string.Format("{0}{1}", filename, extension));
     int i = 0;
     while (i < int.MaxValue)
     {
         if (!File.Exists(newFullName))
         {
             if (!Directory.Exists(directory))
             {
                 Console.WriteLine("Creating folder {0}", directory);
                 Directory.CreateDirectory(directory);
             }
             Console.WriteLine("Moving {0} to {1}", file.FullName, newFullName);
             file.MoveTo(newFullName);
             return;
         }
         else
         {
             Console.WriteLine("Found a file with name {0}; Comparing", newFullName);
             if (FileUtils.FileCompare(file, new FileInfo(newFullName)))
             {
                 Console.WriteLine("Deleting duplicate file {0}", file.FullName);
                 file.Delete();
                 return;
             }
             newFullName = Path.Combine(directory,
                 string.Format("{0}_{1}{2}", filename, ++i, extension));
         }
     }
 }
        public void renombrar(bool online, string nombre_viejo, string nombre_nuevo)
        {
            string sourceFile;

            if (!online)
            {
                sourceFile = @configuracion.carpetas.ruta_subir_servidor_carpeta + "\\";
            }
            else
            {
                sourceFile = @configuracion.carpetas.ruta_imagenes_carpeta + "\\";
            }

            // Create a FileInfo
            System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile + nombre_viejo);
            // Check if file is there
            if (fi.Exists)
            {
                //System.Windows.MessageBox.Show("Si esta");
                // Move file with a new name. Hence renamed.
                fi.MoveTo(sourceFile + nombre_nuevo);
                //string destFile = System.IO.Path.Combine(@"\\DESKTOP-ED8E774\bs\", nombre_nuevo);
                //System.IO.File.Copy(@"\\DESKTOP-ED8E774\fotos_offline\" + nombre_nuevo, destFile, true);
                //System.Windows.MessageBox.Show("se pudo si");
            }
        }
        /// <summary>
        /// The normal PDF archival method.
        /// </summary>
        /// <param name="pdfFile">The PDF file.</param>
        /// <param name="archiveDirectory">The archive directory.</param>
        public static void ArchiveNormal(FileInfo pdfFile, string archiveDirectory)
        {
            // Create a new subdirectory in the archive directory
            // This is based on the date of the report being archived
            DirectoryInfo di = new DirectoryInfo(archiveDirectory);
            string archiveFileName = pdfFile.Name;
            string newSubFolder = ParseFolderName(archiveFileName);
            try
            {
                di.CreateSubdirectory(newSubFolder);
            }
            catch (Exception ex)
            {
                // The folder already exists so don't create it
            }

            // Create destination path
            string destFullPath = archiveDirectory + "\\" + newSubFolder + "\\" + pdfFile.Name;

            // Move the file to the archive directory
            try
            {
                pdfFile.MoveTo(destFullPath);
            }
            catch (Exception ex)
            {
                // Unable to move the PDF to the archive
            }
        }
    // Move file to destination directory and create the directory when none exists.
    public static void MoveFileToDirectory(string srcFilePath, string destDir)
    {
        var fi = new System.IO.FileInfo(srcFilePath);

        if (!fi.Exists)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to move. Source is missing: {0}.", srcFilePath));
            return;
        }

        var di = new System.IO.DirectoryInfo(destDir);

        if (!di.Exists)
        {
            di.Create();
        }

        string destFilePath = System.IO.Path.Combine(di.FullName, fi.Name);

        try
        {
            fi.MoveTo(destFilePath);
        }
        catch (Exception ex)
        {
            UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message));
            return;
        }

        return;
    }
Example #16
0
        public void SetupReporting()
        {
            //driverManager.extentIEMethod();



            Console.WriteLine(" Onetime Setup for IE!!");
            htmlReporter = new ExtentHtmlReporter(@"D:\SlkSeleniumFramework\TestProjectSample\TestProjectCL\UnitTest\UnitTestProject1\Reports\ie\index.html");
            string sourceFile = @"D:\SlkSeleniumFramework\TestProjectSample\TestProjectCL\UnitTest\UnitTestProject1\Reports\ie\index.html";

            //   htmlReporter = new ExtentHtmlReporter(@"projectDirectory\Reports\ie\index.html");
            //     string sourceFile = @"projectDirectory\Reports\ie\index.html";
            System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
            if (fi.Exists)
            {
                Console.WriteLine(" The file exists-Onetime Setup for IE!!");
                //  fi.MoveTo(@"projectDirectory\Reports\ie\Extentreport-" + timeStamp + ".html");
                fi.MoveTo(@"D:\SlkSeleniumFramework\TestProjectSample\TestProjectCL\UnitTest\UnitTestProject1\Reports\ie\Extentreport-" + timeStamp + ".html");

                Console.WriteLine(" IE File Renamed!!");
            }



            extent = new ExtentReports();
            extent.AttachReporter(htmlReporter);
            Console.WriteLine("The Extent Report is generated.");
        }
Example #17
0
        /*for create a file end*/



        /*For rename file function start*/

        public void RenameFile()
        {
            string filepath = @"C:\Users\DELL\Desktop\radixfile\";

            Console.Write("Enter FileName (use .txt extension) : ");
            string fileName = Console.ReadLine();
            string Path     = filepath + fileName;

            FileInfo fileInfo = new System.IO.FileInfo(Path);

            if (fileInfo.Exists)
            {
                Console.Write("Enter FileName (use .txt extension) : ");
                string newName = Console.ReadLine();
                string newPath = filepath + newName;
                fileInfo.MoveTo(newPath);
                Console.WriteLine("File Rename Successfully");
                Menu();
            }
            else
            {
                Console.WriteLine("File Not exist");
                Menu();
            }
        }
Example #18
0
        }// [DONE]

        // FILE MANAGEMENT:
        private bool fileRenaming(String oldFileName, String newFileName, String directory)
        {
            oldFileName = oldFileName.Insert(0, directory + "/");
            newFileName = newFileName.Insert(0, directory + "/");

            System.IO.FileInfo file = new System.IO.FileInfo(oldFileName);

            if (file.Exists)
            {
                // Try to move and rename the file:
                try
                {
                    file.MoveTo(newFileName);
                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }//[DONE]
Example #19
0
        /// <summary>
        /// 新建活动
        /// </summary>
        /// <param name="name">活动名称</param>
        /// <param name="poster">宣传海报</param>
        /// <param name="begintime">开始时间</param>
        /// <param name="endtime">结束时间</param>
        /// <param name="address">地址</param>
        /// <param name="ownerid">负责人(联系人)</param>
        /// <param name="remark">描述</param>
        /// <param name="userid">创建人</param>
        /// <param name="agentid">代理商ID</param>
        /// <param name="clientid">客户端ID</param>
        /// <returns></returns>
        public static string CreateActivity(string name, string poster, string begintime, string endtime, string address, string ownerid, string memberid, string remark, string userid, string agentid, string clientid)
        {
            string activityid = Guid.NewGuid().ToString();

            if (!string.IsNullOrEmpty(poster))
            {
                if (poster.IndexOf("?") > 0)
                {
                    poster = poster.Substring(0, poster.IndexOf("?"));
                }
                FileInfo file = new FileInfo(HttpContext.Current.Server.MapPath(poster));
                poster = FilePath + file.Name;
                if (file.Exists)
                {
                    file.MoveTo(HttpContext.Current.Server.MapPath(poster));
                }
            }
            bool bl = ActivityDAL.BaseProvider.CreateActivity(activityid, name, poster, begintime, endtime, address, ownerid,memberid, remark, userid, agentid, clientid);
            if (!bl)
            {
                return "";
            }
            else
            {
                //日志
                LogBusiness.AddActionLog(CloudSalesEnum.EnumSystemType.Client, CloudSalesEnum.EnumLogObjectType.Activity, EnumLogType.Create, "", userid, agentid, clientid);
            }
            return activityid;
        }
Example #20
0
        /// <summary>
        /// Converts the file
        /// </summary>
        /// <param name="fileName">The path to the file which should become converted</param>
        /// <param name="newFileName">The name of the new file WITHOUT extension</param>
        /// <param name="bitrate">The audio bitrate</param>
        /// <param name="format"></param>
        public static async Task ConvertFile(string fileName, string newFileName, AudioBitrate bitrate, AudioFormat format)
        {
            var fileToConvert = new FileInfo(fileName);

            var p = new Process
            {
                StartInfo =
                {
                    CreateNoWindow = true,
                    FileName = HurricaneSettings.Paths.FFmpegPath,
                    Arguments = GetParameter(fileName, newFileName, bitrate, format),
                    UseShellExecute = false
                }
            };

            p.Start();
            await Task.Run(() => p.WaitForExit());
            var newFile = new FileInfo(newFileName);

            if (!newFile.Exists || newFile.Length == 0)
            {
                if (newFile.Exists) newFile.Delete();
                fileToConvert.MoveTo(newFileName); //If the convert failed, we just use the "old" file
            }

            fileToConvert.Delete();
        }
Example #21
0
        private void AfterParse(IAsyncResult result)
        {
            try
            {
                Watcher watcher = result.AsyncState as Watcher;

                FileInfo file = new FileInfo(watcher.CurrentFile);

                switch (watcher.LastAction)
                {
                    case "0":
                        break;
                    case "1":
                        file.Delete();
                        break;
                    case "2":
                        {
                            string destFilename = Path.Combine(watcher.LastPath, file.Name);
                            File.Delete(destFilename);
                            file.MoveTo(destFilename);
                        }
                        break;
                }
                file = null;
            }
            catch
            {

            }
        }
Example #22
0
 private static int Main(string[] args)
 {
     if (args.Length < 3)
     {
         Console.Out.WriteLine("Versioning [Msi Package] [Dll] [New Filename]");
         return 0;
     }
     FileInfo info = new FileInfo(args[0]);
     FileInfo file = new FileInfo(args[1]);
     string format = args[2];
     if (!info.Exists)
     {
         Console.Out.WriteLine("Unable to find msi package: " + args[0]);
     }
     if (!file.Exists)
     {
         Console.Out.WriteLine("Unable to find dll" + args[1]);
     }
     if (!info.Exists || !file.Exists)
     {
         return 8;
     }
     string version = GetVersion(file);
     string destFileName = string.Format(format, version);
     info.MoveTo(destFileName);
     return 0;
 }
        private void AfterHandle(IAsyncResult result)
        {
            try
            {
                Watcher watcher = result.AsyncState as Watcher;

                FileInfo file = new FileInfo(watcher.CurrentFile);

                AfterProcessAction action = (AfterProcessAction)Enum.Parse(typeof(AfterProcessAction), watcher.LastAction, true);

                switch (action)
                {
                    case AfterProcessAction.None:
                        break;
                    case AfterProcessAction.Delete:
                        file.Delete();
                        Logger.sysLog.InfoFormat("Bank report [{0}] was deleted", watcher.CurrentFile);
                        break;
                    case AfterProcessAction.Backup:
                        {
                            string destFilename = Path.Combine(watcher.LastPath, file.Name);
                            File.Delete(destFilename);
                            file.MoveTo(destFilename);
                            Logger.sysLog.InfoFormat("Bank report was moved to [{0}]", destFilename);
                        }
                        break;
                }
                file = null;
            }
            catch
            {

            }
        }
Example #24
0
 private async Task RenameImages(List <string> fileList, string rootFolder, string folder, string prefixName, string lastImageName)
 {
     await Task.Run(() =>
     {
         int cout = 1;
         for (int i = 0; i < fileList.Count; i++)
         {
             var fileExtension = Path.GetExtension(fileList[i]);
             var fileName      = Path.GetFileName(fileList[i]).Replace(fileExtension, "");
             if (fileName.Equals(prefixName))
             {
                 break;
             }
             // Create a FileInfo
             System.IO.FileInfo fi = new System.IO.FileInfo(fileList[i]);
             string des            = rootFolder + "\\" + folder + "\\" + prefixName + " (" + cout + ")" + fileExtension;
             if ((prefixName + " (" + cout + ")").Equals(lastImageName))
             {
                 des = rootFolder + "\\" + folder + "\\" + prefixName + fileExtension;
             }
             fi.MoveTo(des);
             cout++;
         }
     });
 }
Example #25
0
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            System.IO.FileInfo file = new System.IO.FileInfo(hidPath.Value + @"\" + hidName.Value);
            System.IO.FileInfo newfile = new System.IO.FileInfo(hidPath.Value + @"\" + txtFileName.Text);
            if (newfile.Exists)
            {
                lblError.Text = "<font color='red'> 文件" + txtFileName.Text + "已经存在。</font>";
            }
            else
            {
                file.MoveTo(hidPath.Value + @"\" + txtFileName.Text);
                //Response.Write("<script>parent.frames('_netDiskLeft').location.href='../Netdisk/Left.aspx';</script>");
                //Response.Write("<script>parent.frames('_netDiskMain').location.href='../Netdisk/FileList.aspx?path=" + hidPath.Value.Replace(@"\", @"\\") + "';</script>");

                //Response.Write("<script>window.open('../Netdisk/Left.aspx','_netDiskLeft');</script>");
                //Response.Write("<script>window.open('../Netdisk/FileList.aspx?path=" +Server.UrlEncode( hidPath.Value.Replace(@"\", @"\\")) + "','_netDiskMain');</script>");
                Response.Write("<script>location='../Netdisk/FileList.aspx?path=" + Server.UrlEncode(hidPath.Value) + "';</script>");
                divSucccess.Visible = true;
                divCreateFolder.Visible = false;
            }
        }
        catch (Exception ee)
        {
            lblError.Text = "<font color='red'>文件重命名失败:" + ee.Message + "</font>";
        }
    }
Example #26
0
        public void replaceDB()
        {
            //replace DB
            System.IO.FileInfo fi  = new System.IO.FileInfo(SharedVar.dbpath);
            System.IO.FileInfo fin = new System.IO.FileInfo(SharedVar.newDbPath);
            System.IO.FileInfo fib = new System.IO.FileInfo(SharedVar.bkDbPath);
            try
            {
                if (fib.Exists)
                {
                    fib.Delete();
                    Console.WriteLine("ex bk deleted.");
                }
                if (fi.Exists)
                {
                    GC.Collect();
                    // GC.WaitForPendingFinalizers();

                    fi.MoveTo(SharedVar.bkDbPath);
                    Console.WriteLine("BK ok.");
                }

                if (fin.Exists)
                {
                    fin.MoveTo(SharedVar.dbpath);

                    Console.WriteLine("Update ok.");
                }
            }
            catch
            {
            }
//            File.Replace(SharedVar.newDbPath, SharedVar.dbpath, SharedVar.bkDbPath);
        }
Example #27
0
        public void DeleteTime()
        {
            using (StreamWriter fs = new StreamWriter(file2.ToString(), false, System.Text.Encoding.Default))
            {
                string pl = DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString() + " " + DateTime.Now.Hour.ToString() + ":";

                string str = "";
                Console.WriteLine(pl);
                using (StreamReader reader = new StreamReader(file.ToString(), System.Text.Encoding.Default))
                {
                    while (true)
                    {
                        if (reader.EndOfStream)
                        {
                            break;
                        }
                        srt = reader.ReadLine();
                        if (str.Contains(pl))
                        {
                            fs.WriteLine(str);
                        }
                    }
                }
            }
            file.Delete();
            file2.MoveTo("C://for13lab//LOGfile.txt");
        }
Example #28
0
        public static string UploadedFileMoveTo(string sourcePath,string targetPath)
        {
            var file = new FileInfo(sourcePath);
            file.MoveTo(targetPath);

            Directory.CreateDirectory(Path.GetDirectoryName(targetPath));
            return file.Name;
        }
Example #29
0
    /// <summary>
    /// 在磁盘中移动文件夹
    /// </summary>
    /// <param name="filePath">文件夹的源路径</param>
    /// <param name="moveToPath">目标路径</param>
    private bool MoveFolder(string filePath, string moveToPath)
    {
        try
        {
            Directory.CreateDirectory(moveToPath);

            //下面所有的代码都是在路径正确的情况下(即盘符路径间的分隔符为"\")
            string filename = Path.GetFileName(filePath); //获得要移动的文件夹名(将在目标路径创建个此名字命名的文件夹)
            //判断路径结尾是否是"\"  没有就加上去  path为处理过的正确的目标路径
            string path = (moveToPath.LastIndexOf(Path.DirectorySeparatorChar) == moveToPath.Length - 1) ? moveToPath : moveToPath + Path.DirectorySeparatorChar;
            if (Path.GetPathRoot(filePath) == Path.GetPathRoot(moveToPath))
            {
                if (Directory.Exists(path + filename))
                {
                    Directory.Delete(path + filename, true);
                }
                Directory.Move(filePath, path + filename);
            }
            else
            {
                string parent = Path.GetDirectoryName(filePath);
                Directory.CreateDirectory(path + Path.GetFileName(filePath));
                DirectoryInfo          dir     = new DirectoryInfo((filePath.LastIndexOf(Path.DirectorySeparatorChar) == filePath.Length - 1) ? filePath : filePath + Path.DirectorySeparatorChar);
                FileSystemInfo[]       fileArr = dir.GetFileSystemInfos();
                Queue <FileSystemInfo> Folders = new Queue <FileSystemInfo>(dir.GetFileSystemInfos());
                //循环源路径下的所有文件
                while (Folders.Count > 0)
                {
                    FileSystemInfo tmp = Folders.Dequeue();
                    //转换为文件
                    System.IO.FileInfo f = tmp as System.IO.FileInfo;
                    //为空即是文件夹  创建文件夹
                    if (f == null)
                    {
                        DirectoryInfo d     = tmp as DirectoryInfo;
                        DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf(Path.DirectorySeparatorChar) == parent.Length - 1) ? parent : parent + Path.DirectorySeparatorChar, path));
                        dpath.Create();
                        foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                        {
                            Folders.Enqueue(fi);
                        }
                    }
                    //否则移动文件
                    else
                    {
                        f.MoveTo(f.FullName.Replace(parent, path));
                    }
                }
                //最后清空源路径的文件夹
                Directory.Delete(filePath, true);
            }
            return(true);
        }
        catch (Exception ex)
        {
            return(false);
        }
    }
Example #30
0
 public void UpdatePublishState(IList<MarkdownFile> files)
 {
     foreach (var f in files)
     {
         var p = Path.Combine(_path, f.Name);
         var fi = new FileInfo(p);
         fi.MoveTo(Path.Combine(_path, f.PublishedName));
     }
 }
Example #31
0
        public override void Save(string programPath)
        {
            var tempFile = new FileInfo(Path.GetTempFileName());
            Save<PlaylistSettings>(tempFile.FullName);

            var settingsFile = new FileInfo(Path.Combine(programPath, Filename));
            if (settingsFile.Exists) settingsFile.Delete();
            tempFile.MoveTo(settingsFile.FullName);
        }
Example #32
0
 public void ChangeExtention()
 {
     string MyLogFile = Application.StartupPath + "\\DLL Versions.txt";
     FileInfo file = new FileInfo(MyLogFile);
     MyHtmlDeletion();
     string newPath = Path.ChangeExtension(MyLogFile, ".html");
     file.MoveTo(newPath);
     MytxtDeletion();
 }
Example #33
0
        public override VisitanteViewModel AfterInsert(VisitanteViewModel value)
        {
            try
            {
                #region Check if has file to transfer from Temp Folder to Users_Data Folder
                if (value.Fotografia != null && value.Fotografia != "")
                {
                    #region Check if directory "arquivos" exists. If do not, create it
                    // Define destination
                    var folderName = "/Users_Data/Empresas/" + sessaoCorrente.empresaId.ToString() + "/Visitante";
                    var serverPath = System.Web.HttpContext.Current.Server.MapPath(folderName);
                    if (Directory.Exists(serverPath) == false)
                    {
                        Directory.CreateDirectory(serverPath);
                    }
                    #endregion

                    #region Move the file from Temp Folder to Users_Data Folder
                    System.IO.FileInfo f = new System.IO.FileInfo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Temp"), value.Fotografia));
                    if (f.Exists)
                    {
                        f.MoveTo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Users_Data/Empresas/" + sessaoCorrente.empresaId.ToString() + "/Visitante"), value.Fotografia));
                    }
                    #endregion
                }
                #endregion
            }
            catch (DirectoryNotFoundException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Path de armazenamento do arquivo de boleto/comprovante não encontrado";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (FileNotFoundException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Arquivo de boleto/comprovante não encontrado";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (IOException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Erro referente ao arquivo de boleto/comprovante";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (Exception ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message;
                value.mensagem.MessageType = MsgType.ERROR;
            }
            return(value);
        }
Example #34
0
File: IO.cs Project: jhogan/qed
 public static void OverwriteFile(FileInfo file, string with)
 {
     FileInfo tmp = new FileInfo(file.FullName + ".tmp");
     StreamWriter sw = new StreamWriter(tmp.FullName);
     sw.Write(with);
     sw.Close();
     file.Delete();
     tmp.MoveTo(file.FullName);
 }
Example #35
0
        static void Main(string[] args)
        {
            Console.WriteLine("reading drives\n");
            foreach (DriveInfo drive in DriveInfo.GetDrives())
            {
                Console.WriteLine("{0} : {1}",drive.Name, drive.DriveType);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("reading directories\n");

            DirectoryInfo dirInfo = new DirectoryInfo(@"C:\");
            foreach (DirectoryInfo item in dirInfo.GetDirectories())
            {
                Console.WriteLine(item.FullName);
            }
            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("read files");
            foreach (FileInfo item in dirInfo.GetFiles())
            {
                Console.WriteLine(item.FullName);
            }

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("Create directory");
            DirectoryInfo newDir = new DirectoryInfo(@"C:\DeleteMe");
            if (!newDir.Exists)
            {
                newDir.Create();
                Console.WriteLine("Folder created");
            }
            else
                Console.WriteLine("Directory already exists.");

            Console.ReadLine();

            Console.Clear();
            Console.WriteLine("creating file");
            FileInfo fInfo = new FileInfo(@"C:\deleteme\mynewfile.txt");
            fInfo.CreateText();

            Console.WriteLine("copy file");
            fInfo.CopyTo(@"c:\deleteme\Mycopiedfile.txt");

            Console.WriteLine("move file");
            FileInfo fInfo2 = new FileInfo(@"C:\deleteme\MycopiedFile.txt");
            fInfo2.MoveTo(@"c:\deleteme\mythirdfile.txt");

            Console.WriteLine("done");
            Console.ReadLine();
        }
Example #36
0
 //静态方法。移动文件微操作。
 public static void Mov(FileInfo srcPath, string desPath, MoveMethod movemethod)
 {
     int IndexNum = 0;
     switch(movemethod)
     {
         case MoveMethod.Dirc: //直接移动。不做任何异常处理
             srcPath.MoveTo(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + srcPath.Extension);
             break;
         case MoveMethod.OverR://覆盖(先删除后移动),如果无权删除,则重命名
             try
             {
                 File.Delete(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + srcPath.Extension);
                 srcPath.MoveTo(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + srcPath.Extension);
             }
             catch(UnauthorizedAccessException)
             {
                 //如果有重名,则加上_n后缀。n从1开始直到不重名为止。n不大于100000,避免死循环
                 for (int i = 0; i < 100000; i++)
                 {
                     if (!File.Exists(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + @"_" + i.ToString() + srcPath.Extension))
                     {
                         IndexNum = i;
                         break;
                     }
                 }
                 srcPath.MoveTo(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + @"_" + IndexNum.ToString() + srcPath.Extension);
             }
             break;
         case MoveMethod.Ren://重命名后移动
             //如果有重名,则加上_n后缀。n从1开始直到不重名为止。n不大于100000,避免死循环
             for (int i = 0; i < 100000; i++)
             {
                 if (!File.Exists(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + @"_" + i.ToString() + srcPath.Extension))
                 {
                     IndexNum = i;
                     break;
                 }
             }
             srcPath.MoveTo(desPath + "\\" + Path.GetFileNameWithoutExtension(srcPath.FullName) + @"_" + IndexNum.ToString() + srcPath.Extension);
             break;
         case MoveMethod.None://跳过
             break;
     }
 }
Example #37
0
 public void Handle(FileInfo fi, TorrentHandler th)
 {
     var friendly = fi.Name.TorrentName();
     var di = new FileInfo(@"C:\home\media\tv\" + friendly + fi.Extension);
     if (di.Exists)
         di.Delete();
     fi.MoveTo(di.FullName);
     Brain.Pipe.ListenNext((s, match, listener) => Process.Start(di.FullName), "play|open|ok");
     Brain.ListenerManager.CurrentListener.Output("{0} is ready to be watched.".Template(friendly));
 }
Example #38
0
        void RenameFile(FileInfo source, FileInfo destination)
        {
            string path = _path.Combine(source.Directory.FullName, destination.Name);

            if (File.Exists(path)){File.Delete(path);}

            source.MoveTo(path);
            _log.DebugFormat("Rename file '{0}' destination '{1}'", source.FullName, destination.FullName);
            _fileLog.Info(destination); //log where files are copied for tripwire
        }
Example #39
0
 // metoda zmieniająca nazwę pliku lokalnego
 public void RenameFileOnLocal(string oldFileName, string Path, string newFileName)
 {
     System.IO.FileInfo fi = new System.IO.FileInfo(Path + "\\" + oldFileName);
     // Sprawdzenie gdzie się znajduje ostatni znacznik separujący katalogi
     try
     {
         fi.MoveTo(Path + "\\" + newFileName);
     }
     catch (System.IO.IOException e) {}
 }
Example #40
0
        public override void Execute(string filename, bool testModus, Job job) {
            Console.WriteLine("  Rename '{0}' to '{1}", filename, job.Parameter2);
            if (testModus) {
                return;
            }
            var file = new FileInfo(filename);
            var destFileName = Path.Combine(file.DirectoryName, job.Parameter2);

            file.MoveTo(destFileName);
        }
Example #41
0
        /// <inheritdoc/>
        protected override void CopyFile(FileInfo sourceFile, FileInfo destinationFile)
        {
            #region Sanity checks
            if (sourceFile == null) throw new ArgumentNullException(nameof(sourceFile));
            if (destinationFile == null) throw new ArgumentNullException(nameof(destinationFile));
            #endregion

            if (Overwrite && destinationFile.Exists) destinationFile.Delete();
            sourceFile.MoveTo(destinationFile.FullName);
        }
Example #42
0
        /// <summary>
        /// Add CRC checksum to given filename.
        /// </summary>
        /// <param name="filename">The fullpath filename.</param>
        /// <param name="crc">The CRC code.</param>
        /// <param name="newfilename">Just the filename.</param>
        /// <returns>The fullpath filename.</returns>
        public static string AddCRC(string filename, string crc, out string newfilename)
        {
            FileInfo file = new FileInfo(filename);
            file.Refresh();

            file.MoveTo(file.FullName.Insert(file.FullName.Length - (file.Extension.Length), "_[" + crc + "]"));
            file.Refresh();
            newfilename = Path.GetFileName(file.Name);
            return file.FullName;
        }
Example #43
0
    static void PrepareIntegration()
    {
        if (!UnityEditorInternal.InternalEditorUtility.HasPro())
        {
            Debug.Log("Unity basic license detected: running integration in Basic compatible mode");

            // Copy the FMOD binaries to the root directory of the project
            if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                var pluginPath  = Application.dataPath + "/Plugins/x86/";
                var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;

                var fmodFile = new System.IO.FileInfo(pluginPath + "fmod.dll");
                if (fmodFile.Exists)
                {
                    var dest = projectRoot.FullName + "/fmod.dll";

                    DeleteBinaryFile(dest);
                    fmodFile.MoveTo(dest);
                }

                var studioFile = new System.IO.FileInfo(pluginPath + "fmodstudio.dll");
                if (studioFile.Exists)
                {
                    var dest = projectRoot.FullName + "/fmodstudio.dll";

                    DeleteBinaryFile(dest);
                    studioFile.MoveTo(dest);
                }
            }
            else if (Application.platform == RuntimePlatform.OSXEditor)
            {
                var pluginPath  = Application.dataPath + "/Plugins/";
                var projectRoot = new System.IO.DirectoryInfo(Application.dataPath).Parent;

                var fmodFile = new System.IO.FileInfo(pluginPath + "fmod.bundle/Contents/MacOS/fmod");
                if (fmodFile.Exists)
                {
                    var dest = projectRoot.FullName + "/fmod.dylib";

                    DeleteBinaryFile(dest);
                    fmodFile.MoveTo(dest);
                }

                var studioFile = new System.IO.FileInfo(pluginPath + "fmodstudio.bundle/Contents/MacOS/fmodstudio");
                if (studioFile.Exists)
                {
                    var dest = projectRoot.FullName + "/fmodstudio.dylib";

                    DeleteBinaryFile(dest);
                    studioFile.MoveTo(dest);
                }
            }
        }
    }
Example #44
0
        /// <summary>
        /// 해당 일이 지난 파일을 지정된 폴더로 이동합니다
        /// </summary>
        /// <param name="dirName">파일들을 찾을 위치</param>
        /// <param name="dirBaseTo">년월로 폴더를 생성할 위치</param>
        /// <param name="dayOld">이동 조건 일(Day)</param>
        /// <param name="isCheckWriteTIme">True이면 수정 날짜로 체크, False이면 파일 이름 및 폴더 이름으로 체크</param>
        public static void MoveToMonthDirOldFile(string dirName, string dirBaseTo, int dayOld, bool isCheckWriteTIme = true)
        {
            if (dirName == "")
            {
                return;
            }

            if (!System.IO.Directory.Exists(dirName))
            {
                return;
            }

            string[] files = System.IO.Directory.GetFiles(dirName);

            string dirMoveTo = "";

            foreach (string file in files)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(file);

                bool isMove = false;
                if (isCheckWriteTIme)
                {
                    isMove = fi.LastWriteTime < DateTime.Now.AddDays(-dayOld);
                }
                else
                {
                    DateTime dt;
                    if (!DateTime.TryParse(fi.Name, out dt))
                    {
                        return;
                    }

                    isMove = dt < DateTime.Now.AddDays(-dayOld);
                }

                if (isMove)
                {
                    try
                    {
                        dirMoveTo = string.Format("{0}\\{1}", dirBaseTo, fi.LastWriteTime.ToString("yyyy-MM"));
                        if (!System.IO.Directory.Exists(dirMoveTo))
                        {
                            System.IO.Directory.CreateDirectory(dirMoveTo);
                        }

                        fi.MoveTo(string.Format("{0}\\{1}", dirMoveTo, fi.Name));
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Example #45
0
        private void demoteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PictureBox pb = (PictureBox)((ContextMenu)((MenuItem)sender).Parent).SourceControl;

            System.IO.FileInfo f = new System.IO.FileInfo(pb.ImageLocation);

            // Assumes \..\- exists...
            f.MoveTo(f.DirectoryName + "\\..\\-\\" + f.Name);
            pictureBox1.ImageLocation = "";
            flowLayoutPanel1.Controls.Remove(pb);
        }
Example #46
0
        /// <summary>
        /// 利用线程来移动文件(这个过程略废CPU)
        /// </summary>
        /// <param name="oSynchronizeFileQueue"></param>
        public void ThreadMoveTo(object oSynchronizeFileQueue)
        {
            List <String> SynchronizeFileQueue = oSynchronizeFileQueue as List <String>;

            if (SynchronizeFileQueue != null && SynchronizeFileQueue.Count == 2)
            {
                System.IO.FileInfo SynchronizeFile = new System.IO.FileInfo(SynchronizeFileQueue[0]);
                if (SynchronizeFile.Exists)
                {
                    SynchronizeFile.MoveTo(SynchronizeFileQueue[1]);
                }
            }
        }
Example #47
0
        public async Task TestImportThenImportWithDifferentFilename()
        {
            using (HeadlessGameHost host = new CleanRunHeadlessGameHost(nameof(ImportBeatmapTest)))
            {
                try
                {
                    var osu = LoadOsuIntoHost(host);

                    var temp = TestResources.GetTestBeatmapForImport();

                    string extractedFolder = $"{temp}_extracted";
                    Directory.CreateDirectory(extractedFolder);

                    try
                    {
                        var imported = await LoadOszIntoOsu(osu);

                        using (var zip = ZipArchive.Open(temp))
                            zip.WriteToDirectory(extractedFolder);

                        // change filename
                        var firstFile = new FileInfo(Directory.GetFiles(extractedFolder).First());
                        firstFile.MoveTo(Path.Combine(firstFile.DirectoryName.AsNonNull(), $"{firstFile.Name}-changed{firstFile.Extension}"));

                        using (var zip = ZipArchive.Create())
                        {
                            zip.AddAllFromDirectory(extractedFolder);
                            zip.SaveTo(temp, new ZipWriterOptions(CompressionType.Deflate));
                        }

                        var importedSecondTime = await osu.Dependencies.Get <BeatmapManager>().Import(new ImportTask(temp));

                        ensureLoaded(osu);

                        // check the newly "imported" beatmap is not the original.
                        Assert.IsTrue(imported.ID != importedSecondTime.ID);
                        Assert.IsTrue(imported.Beatmaps.First().ID != importedSecondTime.Beatmaps.First().ID);
                    }
                    finally
                    {
                        Directory.Delete(extractedFolder, true);
                    }
                }
                finally
                {
                    host.Exit();
                }
            }
        }
Example #48
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="fInfo"></param>
        /// <returns></returns>
        private string parseExtForView(System.IO.FileInfo fInfo)
        {
            string srtReturn = fInfo.Name;

            if (fInfo.Extension == ".aspx")
            {
                srtReturn = fInfo.Name.Substring(0, (fInfo.Name.Length - fInfo.Extension.Length));
            }
            else
            {
                fInfo.MoveTo(fInfo.FullName + ".aspx");
                parseExtForView(fInfo);
            }
            return(srtReturn);
        }
Example #49
0
 public void Rename()
 {
     if (SelectedFileInfo != null && SelectedFileInfo.Status == Statuses.COMPLETED)
     {
         System.IO.FileInfo fi   = new System.IO.FileInfo(Path.Combine(selectedFileInfo.FolderPath, selectedFileInfo.Name));
         string             path = Path.Combine(selectedFileInfo.FolderPath, name + Path.GetExtension(selectedFileInfo.Name));
         path = FreePath(path);
         if (!File.Exists(path) && File.Exists(Path.Combine(selectedFileInfo.FolderPath, selectedFileInfo.Name)))
         {
             fi.MoveTo(Path.Combine(selectedFileInfo.FolderPath, Path.GetFileNameWithoutExtension(path) + Path.GetExtension(path)));
         }
         SelectedFileInfo.Name = Path.GetFileName(path);
         Name = String.Empty;
     }
 }
Example #50
0
 public void SetFileName(string name)
 {
     System.IO.FileInfo file = new System.IO.FileInfo(ResInfo.FileFullName);
     if (File.Exists(file.DirectoryName + "/" + name))
     {
         SetFileName("副本-" + name);
     }
     else
     {
         ResInfo.FileName     = name;
         FileName.text        = name;
         ResInfo.FileFullName = file.DirectoryName + "/" + name;
         file.MoveTo(file.DirectoryName + "/" + name);
     }
 }
Example #51
0
        /// <summary>
        /// ファイルのリネームを行う
        /// 退会若しくは期限切れ時にアンインストールだと手動対応を行わなけれならないので
        /// 代わりにリネームして該当ファイルを使えなくする
        /// 対象ファイルを操作する前に必ず使用されていない状態にする必要があります
        /// </summary>
        /// <param name="file_full_path">リネーム対象のファイルフルパス</param>
        /// <param name="orign_name">リネームする対象のオリジナルファイル名</param>
        /// <param name="rename">リネーム後のファイル名</param>
        /// <returns></returns>
        public static bool file_rename(string file_full_path, string orign_name, string rename)
        {
            try
            {
                string             rename_file = file_full_path.Replace(orign_name, rename);
                System.IO.FileInfo fi          = new System.IO.FileInfo(file_full_path);

                fi.MoveTo(rename_file);
                return(true);
            }
            catch (System.Exception ex)
            {
                logger.Error(" ファイルリネーム失敗: " + ex.Message);
                return(false);
            }
        }
        // ============================================================================

        public static void File_Move()
        {
            string oldFilePath = @"D:\FileE";
            string newFilePath = @"D:\File3"; // với trường hợp này thì chỉ đơn giản là đổi tên

            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(oldFilePath);
                fileInfo.MoveTo(newFilePath);
            }
            catch
            {
                Console.WriteLine("File does not exist");
                Console.ReadKey();
            }
        }
Example #53
0
        public static bool MoveFile(string oldpath, string newpath)
        {
            bool result;

            try
            {
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(oldpath));
                fileInfo.MoveTo(System.Web.HttpContext.Current.Server.MapPath(newpath));
                result = true;
            }
            catch
            {
                result = false;
            }
            return(result);
        }
Example #54
0
 public override ArquivoViewModel AfterInsert(ArquivoViewModel value)
 {
     try
     {
         #region Check if has file to transfer from Temp Folder to Users_Data Folder
         if (!String.IsNullOrEmpty(value.FileID))
         {
             #region Move the file from Temp Folder to Users_Data Folder
             System.IO.FileInfo f = new System.IO.FileInfo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Temp"), value.FileID));
             if (f.Exists)
             {
                 f.MoveTo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Users_Data/Empresas/" + sessaoCorrente.empresaId.ToString() + "/download"), value.FileID));
             }
             #endregion
         }
         #endregion
     }
     catch (DirectoryNotFoundException ex)
     {
         value.mensagem.Code        = 17;
         value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
         value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Path de armazenamento do arquivo de boleto/comprovante não encontrado";
         value.mensagem.MessageType = MsgType.ERROR;
     }
     catch (FileNotFoundException ex)
     {
         value.mensagem.Code        = 17;
         value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
         value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Arquivo de boleto/comprovante não encontrado";
         value.mensagem.MessageType = MsgType.ERROR;
     }
     catch (IOException ex)
     {
         value.mensagem.Code        = 17;
         value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
         value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Erro referente ao arquivo de boleto/comprovante";
         value.mensagem.MessageType = MsgType.ERROR;
     }
     catch (Exception ex)
     {
         value.mensagem.Code        = 17;
         value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
         value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message;
         value.mensagem.MessageType = MsgType.ERROR;
     }
     return(value);
 }
Example #55
0
        public override EsteiraContabilizacaoViewModel AfterInsert(EsteiraContabilizacaoViewModel value)
        {
            #region Move o arquivo de documento
            try
            {
                #region Check if has file to transfer from Temp Folder to Users_Data Folder
                if (value.arquivo != null && value.arquivo != "")
                {
                    #region Move the file from Temp Folder to Users_Data Folder
                    System.IO.FileInfo f = new System.IO.FileInfo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Temp"), value.arquivo));
                    f.MoveTo(Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Users_Data"), value.arquivo));
                    #endregion
                }
                #endregion
            }
            catch (DirectoryNotFoundException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Path de armazenamento do arquivo de boleto/comprovante não encontrado";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (FileNotFoundException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Arquivo de boleto/comprovante não encontrado";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (IOException ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException != null ? ex.InnerException.InnerException != null ? ex.InnerException.InnerException.Message : ex.InnerException.Message : ex.Message, GetType().FullName).Message + ". Erro referente ao arquivo de boleto/comprovante";
                value.mensagem.MessageType = MsgType.ERROR;
            }
            catch (Exception ex)
            {
                value.mensagem.Code        = 17;
                value.mensagem.Message     = MensagemPadrao.Message(17).ToString();
                value.mensagem.MessageBase = new App_DominioException(ex.InnerException.InnerException.Message ?? ex.Message, GetType().FullName).Message;
                value.mensagem.MessageType = MsgType.ERROR;
            }
            #endregion

            return(base.AfterInsert(value));
        }
        /**
         * If the animation doesn't exist in the cache, null will be returned.
         *
         * Once the animation is successfully parsed, {@link #renameTempFile(FileExtension)} must be
         * called to move the file from a temporary location to its permanent cache location so it can
         * be used in the future.
         */
        //internal async Task<KeyValuePair<FileExtension, Stream>?> FetchAsync(CancellationToken cancellationToken = default(CancellationToken))
        //{
        //    StorageFile cachedFile = null;
        //    try
        //    {
        //        cachedFile = await GetCachedFileAsync(_url, cancellationToken);
        //    }
        //    catch (FileNotFoundException)
        //    {
        //        return null;
        //    }
        //    if (cachedFile == null)
        //    {
        //        return null;
        //    }

        //    Stream inputStream;
        //    try
        //    {
        //        inputStream = await cachedFile.OpenStreamForReadAsync().AsAsyncOperation().AsTask(cancellationToken);
        //    }
        //    catch (FileNotFoundException)
        //    {
        //        return null;
        //    }

        //    FileExtension extension;
        //    if (cachedFile.Path.EndsWith(".zip"))
        //    {
        //        extension = FileExtension.Zip;
        //    }
        //    else
        //    {
        //        extension = FileExtension.Json;
        //    }

        //    Debug.WriteLine("Cache hit for " + _url + " at " + cachedFile.Path, LottieLog.Tag);
        //    return new KeyValuePair<FileExtension, Stream>(extension, inputStream);
        //}

        ///// <summary>
        ///// Writes an InputStream from a network response to a temporary file. If the file successfully parses
        ///// to an composition, {@link #renameTempFile(FileExtension)} should be called to move the file
        ///// to its final location for future cache hits.
        ///// </summary>
        ///// <param name="stream"></param>
        ///// <param name="extension"></param>
        ///// <returns></returns>
        //internal async Task<StorageFile> WriteTempCacheFileAsync(Stream stream, FileExtension extension, CancellationToken cancellationToken = default(CancellationToken))
        //{
        //    var fileName = FilenameForUrl(_url, extension, true);
        //    var file = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting).AsTask(cancellationToken);
        //    try
        //    {
        //        using (var output = await file.OpenStreamForWriteAsync().AsAsyncOperation().AsTask(cancellationToken))
        //        {
        //            await stream.CopyToAsync(output).AsAsyncAction().AsTask(cancellationToken);
        //        }
        //    }
        //    finally
        //    {
        //        stream.Dispose();
        //    }
        //    return file;
        //}

        /// <summary>
        /// If the file created by {@link #writeTempCacheFile(InputStream, FileExtension)} was successfully parsed,
        /// this should be called to remove the temporary part of its name which will allow it to be a cache hit in the future.
        /// </summary>
        /// <param name="extension"></param>
        internal Task RenameTempFileAsync(FileExtension extension, CancellationToken cancellationToken = default(CancellationToken))
        {
            return(Task.Run(() =>
            {
                string fileName = FilenameForUrl(_url, extension, true);
                var file = new System.IO.FileInfo(fileName);
                string newFileName = file.Name.Replace(".temp", "");
                string oldFilename = file.Name;
                try
                {
                    file.MoveTo(newFileName);
                    Debug.WriteLine($"Copying temp file to real file ({file.Name})", LottieLog.Tag);
                }
                catch
                {
                    LottieLog.Warn($"Unable to rename cache file {oldFilename} to {newFileName}.");
                }
            }));
        }
Example #57
0
 private async Task RenameImagesGoiThieu(List <string> fileList, string rootFolder, string folder, string prefixName, string lastImageName)
 {
     await Task.Run(() =>
     {
         if (fileList.Count > 2)
         {
             return;
         }
         var fileExtensionCD = Path.GetExtension(fileList[0]);
         var fileExtensionCR = Path.GetExtension(fileList[0]);
         // Create a FileInfo
         System.IO.FileInfo fiCD = new System.IO.FileInfo(fileList[0]);
         System.IO.FileInfo fiCR = new System.IO.FileInfo(fileList[1]);
         string desCD            = rootFolder + "\\" + folder + "\\CD" + fileExtensionCD;
         string desCR            = rootFolder + "\\" + folder + "\\CR" + fileExtensionCR;
         fiCD.MoveTo(desCD);
         fiCR.MoveTo(desCR);
     });
 }
Example #58
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string sourceFile = Server.MapPath("appointments.csv");

            // Create a FileInfo
            System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
            // Check if file is there
            if (fi.Exists)
            {
                var g = Guid.NewGuid().ToString();
                // Move file with a new name. Hence renamed.
                fi.MoveTo(Server.MapPath("archived_" + g.ToString() + ".csv"));
            }

            // copy back template
            sourceFile = Server.MapPath("~/Data/template.csv");
            string destinationFile = Server.MapPath("~/Data/appointments.csv");

            File.Copy(sourceFile, destinationFile, true);
            Response.Redirect("../Admin.aspx");
        }
Example #59
0
        public void RenameFile()
        {
            Console.WriteLine("Enter FileName Without Any Extension :");
            string fileName = Console.ReadLine();
            string Path     = filepath + fileName + ".txt";

            FileInfo fileInfo = new System.IO.FileInfo(Path);

            if (fileInfo.Exists)
            {
                Console.WriteLine("Enter New FileName Without Any Extension :");
                string newName = Console.ReadLine();
                string newPath = filepath + newName + ".txt";
                fileInfo.MoveTo(newPath);
                Console.WriteLine("File Renamed Successfully");
            }
            else
            {
                Console.WriteLine("File Not exist");
            }
        }
Example #60
-1
        public static void CreatePdfFromHtml(string htmlFilePath)
        {
            var htmlFileInfo = new FileInfo(htmlFilePath);

            if (!htmlFileInfo.Exists)
            {
                throw new FileNotFoundException(htmlFileInfo.FullName);
            }

            Debug.Assert(htmlFileInfo.DirectoryName != null, "htmlFileInfo.DirectoryName != null");

            var tmpPdfFileInfo = new FileInfo(Path.Combine(htmlFileInfo.DirectoryName, "tmp.pdf"));
            var pdfOutFileInfo = new FileInfo(GetPdfEquivalentPath(htmlFileInfo.FullName));

            var gc = new GlobalConfig();

            gc.SetImageQuality(100);
            gc.SetOutputDpi(96);
            gc.SetPaperSize(1024, 1123);

            var oc = new ObjectConfig();

            oc.SetLoadImages(true);
            oc.SetAllowLocalContent(true);
            oc.SetPrintBackground(true);
            oc.SetZoomFactor(1.093);
            oc.SetPageUri(htmlFileInfo.FullName);

            if (tmpPdfFileInfo.Exists)
            {
                tmpPdfFileInfo.Delete();
            }

            IPechkin pechkin = new SynchronizedPechkin(gc);

            pechkin.Error += (converter, text) =>
                {
                    Console.Out.WriteLine("error " + text);
                };

            pechkin.Warning += (converter, text) =>
                {
                    Console.Out.WriteLine("warning " + text);
                };

            using (var file = File.OpenWrite(tmpPdfFileInfo.FullName))
            {
                var bytes = pechkin.Convert(oc);
                file.Write(bytes, 0, bytes.Length);
            }

            if (pdfOutFileInfo.Exists)
            {
                pdfOutFileInfo.Delete();
            }

            CreateDirectories(pdfOutFileInfo.DirectoryName);

            tmpPdfFileInfo.MoveTo(pdfOutFileInfo.FullName);
        }