public static byte[] CreateAgreementDoc(string WebPath, string AgreementNumber, string AgreementDate, string UserName, string SignerName, string TargetPosition, string TargetDepartment, string SignerShortName, string SignerPositionWithDepartment, string UserShortName) { FileInfo file = new FileInfo(Path.Combine(WebPath, @"StaffMovements\Dogovor.docx")); string newfilename = Path.Combine(WebPath,Guid.NewGuid().ToString()+".docx"); var newfile = file.CopyTo(newfilename,true); using (var outputDocument = new TemplateProcessor(newfilename) .SetRemoveContentControls(true)) { var documentenc = Encoding.GetEncoding(outputDocument.Document.Declaration.Encoding); var valuesToFill = new Content( new FieldContent("AgreementNumber", AgreementNumber), new FieldContent("AgreementDate", AgreementDate), new FieldContent("UserName", UserName), new FieldContent("Signer", SignerName), new FieldContent("TargetPosition", TargetPosition), new FieldContent("TargetDepartment", TargetDepartment), new FieldContent("SignerShortName", SignerShortName), new FieldContent("SignerPositionWithDepartment", SignerPositionWithDepartment), new FieldContent("UserShortName", UserShortName) ); outputDocument.FillContent(valuesToFill); outputDocument.SaveChanges(); } StreamReader reader = new StreamReader(newfilename); var result = NoteCreator.ReadFull(reader.BaseStream); //newfile.Delete(); return result; }
private static void CopyFile(string source, string destination, bool overwrite, bool createMissingDirectories, ref int count) { FileInfo sourceFile = new FileInfo(source); //Console.WriteLine("Destination: " + destination); //Console.WriteLine("Directory Name: " + Path.GetDirectoryName(destination)); //Console.WriteLine("File Name: " + Path.GetFileName(destination)); //Console.WriteLine("Extension: " + Path.GetExtension(destination)); if (String.IsNullOrWhiteSpace(Path.GetExtension(destination))) { // destination is a directory DirectoryInfo destinationDirectory = new DirectoryInfo(destination); if (createMissingDirectories && !destinationDirectory.Exists) destinationDirectory.Create(); string destinationFileName = Path.Combine(destinationDirectory.FullName, sourceFile.Name); sourceFile.CopyTo(destinationFileName, overwrite); } else { // destination is a file FileInfo destinationFile = new FileInfo(destination); if (createMissingDirectories && !destinationFile.Directory.Exists) destinationFile.Directory.Create(); string destinationFileName = destinationFile.FullName; sourceFile.CopyTo(destinationFileName, overwrite); } Console.WriteLine(sourceFile.FullName); ++count; }
private bool TryCopyFile(FileInfo sourceFileInfo, DirectoryInfo targetDirectory) { var targetFileInfo = new FileInfo(Combine(targetDirectory, sourceFileInfo.Name)); if (!targetFileInfo.Exists) { try { sourceFileInfo.CopyTo(targetFileInfo.FullName, true); } catch (Exception) { return false; } } if (targetFileInfo.Exists) { if (targetFileInfo.LastWriteTimeUtc < sourceFileInfo.LastWriteTimeUtc) { try { sourceFileInfo.CopyTo(targetFileInfo.FullName, true); Console.Write("."); } catch (Exception) { return false; } } } return true; }
public void Worker() { directory[0].Create(); directory[1].Create(); file = new System.IO.FileInfo("C://for13lab//Inspect//dirinfo.txt"); Add("Создаем файл" + file.ToString()); Add("Записываем информацию о файлах и папках в " + file.ToString()); using (StreamWriter fs = new StreamWriter(file.ToString(), true, System.Text.Encoding.Default)) { foreach (string s in files) { fs.WriteLine(s); } foreach (string s in directories) { fs.WriteLine(s); } Console.WriteLine("Текст записан в файл."); } FileInfo newdirinfo = new FileInfo("C://for13lab//NEWdirinfo.txt"); if (!newdirinfo.Exists) { Add("Копируем dirinfo и удаляем его"); file.CopyTo("C://for13lab//NEWdirinfo.txt"); file.Delete(); } DirectoryInfo fotos = new DirectoryInfo("C://for13lab//Fotos"); Add("Получаем информацию о png файлах в " + fotos.ToString()); System.IO.FileInfo[] jpegFiles = fotos.GetFiles("*.png"); Add($"Копируем файлы png из {fotos.ToString()} в Inspect"); foreach (System.IO.FileInfo file in jpegFiles) { file.CopyTo("C://for13lab//Inspect//" + file.Name, true); } Add("Перемещаем " + directory[1].ToString() + " в " + directory[0].ToString()); directory[1].MoveTo("C://for13lab//Inspect//Files//"); //ZipFile.CreateFromDirectory(directory[0].ToString(), "C://myArchive.zip"); //ZipFile.ExtractToDirectory("C://myArchive.zip", "C://unzip"); Compress("C://for13lab/myfile.txt", "C://for13lab/file.gz"); Add("Файл сжат"); Decompress("C://for13lab/file.gz", "C://for13lab/Unarchived.txt"); Add("Файл восстановлен"); }
/// <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); } } } }
/// <summary> /// 将图片压缩到指定大小 /// </summary> /// <param name="FileName">待压缩图片</param> /// <param name="size">期望压缩后的尺寸</param> public void CompressPhoto(string FileName, int size) { if (!System.IO.File.Exists(FileName)) { return; } int nCount = 0; System.IO.FileInfo oFile = new System.IO.FileInfo(FileName); long nLen = oFile.Length; while (nLen > size * 1024 && nCount < 10) { string dir = oFile.Directory.FullName; string TempFile = System.IO.Path.Combine(dir, Guid.NewGuid().ToString() + "." + oFile.Extension); oFile.CopyTo(TempFile, true); KiSaveAsJPEG(TempFile, FileName, 70); try { System.IO.File.Delete(TempFile); } catch { } nCount++; oFile = new System.IO.FileInfo(FileName); nLen = oFile.Length; } }
public static void Copy(string filePath, string destFolder, bool overwrite) { string name = Path.GetFileName(filePath); string destFilePath = Path.Combine(destFolder, name); FileInfo info = new FileInfo(filePath); info.CopyTo(destFilePath, overwrite); }
protected void Button1_Click(object sender, EventArgs e) { if (!Directory.Exists(Server.MapPath("ProductImageTruePath"))) { Directory.CreateDirectory(Server.MapPath("~/ImageCollection/product/")); } if (File.Exists(Server.MapPath(Image1.ImageUrl))) { System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(Image1.ImageUrl)); file.CopyTo(Server.MapPath(Tools.GetAppSettings("ProductImageTruePath") + Image1.AlternateText)); } if (ddlCategory.SelectedValue != "0") { if (pcBLL.SearchHierarchyUpVail(int.Parse(ddlCategory.SelectedValue), int.Parse(UserInfoConfig.GetUserConfig("HierarchyProductCategory")))) { InsertData(); } else { ShowMessage("新增超越限制階層"); } } else { InsertData(); } }
/// <summary> /// To rename the snapshot for future refernces /// </summary> /// <param name="supportId">supportId</param> public bool Rename(string supportId) { string imgName; string imgPath = ConfigurationManager.AppSettings["SupportSnapShotPath"]; imgName = "img_" + supportId + ".png"; bool ret = false; System.IO.FileInfo fi = new System.IO.FileInfo(imgPath); if (!fi.Exists) { return(ret); } string newFilePathName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(imgPath), imgName); System.IO.FileInfo f2 = new System.IO.FileInfo(newFilePathName); try { if (f2.Exists) { f2.Attributes = System.IO.FileAttributes.Normal; f2.Delete(); } fi.CopyTo(newFilePathName); fi.Delete(); ret = true; } catch { } return(ret); }
private bool renamePicture(string path, string newName) { bool ret = false; System.IO.FileInfo fi = new System.IO.FileInfo(path); newName += fi.Extension; if (!fi.Exists) { return(ret); } string duongdanmoi = Server.MapPath("~/Asset/Images/"); string newFilePathName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(duongdanmoi), newName); System.IO.FileInfo f2 = new System.IO.FileInfo(newFilePathName); try { if (f2.Exists) { f2.Attributes = System.IO.FileAttributes.Normal; f2.Delete(); } fi.CopyTo(newFilePathName); fi.Delete(); ret = true; } catch { } return(ret); }
public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { System.IO.DirectoryInfo sourceDirectory = new System.IO.DirectoryInfo(sourceDirName); if (!sourceDirectory.Exists) { throw new System.IO.DirectoryNotFoundException("Source directory does not exist or could not be found: '{0}'."); } if (!System.IO.Directory.Exists(destDirName)) { System.IO.Directory.CreateDirectory(destDirName); } System.IO.FileInfo[] files = sourceDirectory.GetFiles(); for (int i = 0; i < files.Length; i++) { System.IO.FileInfo file = files[i]; string temppath = System.IO.Path.Combine(destDirName, file.Name); file.CopyTo(temppath, true); } if (copySubDirs) { System.IO.DirectoryInfo[] directories = sourceDirectory.GetDirectories(); for (int i = 0; i < directories.Length; i++) { System.IO.DirectoryInfo subdir = directories[i]; string temppath = System.IO.Path.Combine(destDirName, subdir.Name); SettingsZipper.DirectoryCopy(subdir.FullName, temppath, true); } } }
/// <summary> /// 新建工作空间 /// </summary> /// <param name="Location">路径名</param> /// <param name="Name">文件名</param> public bool CreateWorkspace(string Location, string Name) { string strSrcdb = Application.StartupPath + @"\..\Template\DataConvertTemplate.mdb"; //string strCopyPath = Location + @"\" + Name; string strCopyPath = Location + Name; System.IO.FileInfo fSrcFile = new System.IO.FileInfo(strSrcdb); System.IO.FileInfo fileCopy = new System.IO.FileInfo(strCopyPath); if (fSrcFile.Exists) { if (!fileCopy.Exists) { fSrcFile.CopyTo(strCopyPath); } else { MessageBox.Show("数据库重名!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning); return(false); } } else { IWorkspaceFactory pWorkspaceFactory = new AccessWorkspaceFactoryClass(); pWorkspaceFactory.Create(Location, Name, null, 0); } return(true); }
private void button1_Click_1(object sender, EventArgs e) { if (!Directory.Exists(txtCaminho.Text)) { MessageBox.Show("O diretorio não existe, verifica ai!"); } else { string[] files = System.IO.Directory.GetFiles(txtCaminho.Text, "*.*", SearchOption.TopDirectoryOnly); foreach (string s in files) { System.IO.FileInfo fi = null; try { fi = new System.IO.FileInfo(s); string newName = fi.Name.Substring(0, fi.Name.IndexOf("_")); if (!Directory.Exists(txtCaminho.Text + "\\novas imagens")) { Directory.CreateDirectory(txtCaminho.Text + "\\novas imagens"); } fi.CopyTo(txtCaminho.Text + "\\novas imagens\\" + newName + fi.Extension); } catch { } } MessageBox.Show("Processado!"); } }
public static bool CopySingleFile(System.IO.FileInfo file, string destPath, bool overwriteNewer) { string fileDestPath = System.IO.Path.Combine(destPath, file.Name); //Debug.Log( "Copy '" + file.FullName + "' ----> '" + fileDestPath + "'." ); FileCompareResults results; if (CompareFiles(file.FullName, fileDestPath, out results)) { return(true); } if (!results.TestSucceeded) { Debug.Log("File '" + fileDestPath + "': compare did not succeed."); } if (results.DateResult == eDateCompareResult.SOURCE_NEWER) { Debug.Log("File '" + fileDestPath + "': source is newer."); } if (!overwriteNewer && results.ContentResult == eContentCompareResult.DIFFERENT) { Debug.Log("Destination file '" + fileDestPath + "' is different!"); } if (!overwriteNewer && results.DateResult == eDateCompareResult.DEST_NEWER) { Debug.LogError("Destination file '" + fileDestPath + "' is newer!"); return(false); } try { file.CopyTo(fileDestPath, true); } catch (System.IO.IOException ioex) { Debug.LogError("Failed to copy file '" + fileDestPath + "', reason: " + ioex.Message + ". Is the file checked out?"); return(false); } catch (System.UnauthorizedAccessException) { Debug.LogError("Failed to copy file '" + fileDestPath + "'. Make sure the file is checked out."); return(false); } try { System.IO.FileInfo destFileInfo = new System.IO.FileInfo(fileDestPath); destFileInfo.Attributes = (destFileInfo.Attributes & (~System.IO.FileAttributes.ReadOnly)); } catch (System.IO.IOException) { Debug.LogError("Failed to set destination file '" + fileDestPath + "' to read only after copying. This may cause future copies to fail."); } DebugUtils.Print("Copied file '" + fileDestPath + "'..."); return(true); }
// Modified by K.G for phase2 tasks returned only one link of SkinPackage zip. public string CompressNewSkins(string newFolderName) { var offlineLinks = new OfflineLinks { portalLink = SkinManagerHelper.CompressFolder(portalUploadDir.FullName, skinRootDir.FullName, newFolderName, Res.NewPortalSkinPath), surveyLink = SkinManagerHelper.CompressFolder(surveyUploadDir.FullName, skinRootDir.FullName, newFolderName, Res.NewSurveySkinPath) }; string communityzipPath = SkinManagerHelper.CompressFolder(communityUploadDir.FullName, skinRootDir.FullName, newFolderName, Res.NewCommunitySkinPath); //Added by K.G(24-11-2011) TO Support a third zip package called CommunitySkin.zip FileInfo[] portalSurveyZipFiles = { new FileInfo(offlineLinks.portalLink), new FileInfo(offlineLinks.surveyLink), new FileInfo(communityzipPath) }; //Copied upadted Zipfiles to Skin Package. foreach (var zipFile in portalSurveyZipFiles) { if (zipFile.Length > 0) { if (File.Exists(Path.Combine(skinPackageUploadDir.ToString(), zipFile.Name))) { File.Delete(Path.Combine(skinPackageUploadDir.ToString(), zipFile.Name)); } zipFile.CopyTo(Path.Combine(skinPackageUploadDir.ToString(), zipFile.Name)); } } string SkinPackageLink = SkinManagerHelper.CompressFolder(skinPackageUploadDir.FullName, skinRootDir.FullName, Res.SkinPackageToUploadPath, Res.NewSkinPackagePath); FileInfo SkinPackageFile = new FileInfo(SkinPackageLink); // Done K.G(25/11/2011) copied newly created zip package to portal skin so that it can also be uploaded in the folder under PortalStaging where the rest of the portal skin is uploaded SkinPackageFile.CopyTo(Path.Combine(portalUploadDir.ToString(), SkinPackageFile.Name)); offlineLinks.portalLink = SkinManagerHelper.CompressFolder(portalUploadDir.FullName, skinRootDir.FullName, newFolderName, Res.NewPortalSkinPath); return SkinPackageLink; }
private void GetImg(string fileName, ref ProductInfo product, int index) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); string str = System.Guid.NewGuid().ToString("N", System.Globalization.CultureInfo.InvariantCulture) + System.IO.Path.GetExtension(fileName); string text = this.uploadPath + "/images/" + str; string text2 = this.uploadPath + "/thumbs40/40_" + str; string text3 = this.uploadPath + "/thumbs60/60_" + str; string text4 = this.uploadPath + "/thumbs100/100_" + str; string text5 = this.uploadPath + "/thumbs160/160_" + str; string text6 = this.uploadPath + "/thumbs180/180_" + str; string text7 = this.uploadPath + "/thumbs220/220_" + str; string text8 = this.uploadPath + "/thumbs310/310_" + str; string text9 = this.uploadPath + "/thumbs410/410_" + str; fileInfo.CopyTo(base.Request.MapPath(Globals.ApplicationPath + text)); string sourceFilename = base.Request.MapPath(Globals.ApplicationPath + text); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text2), 40, 40); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text3), 60, 60); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text4), 100, 100); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text5), 160, 160); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text6), 180, 180); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text7), 220, 220); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text8), 310, 310); ResourcesHelper.CreateThumbnail(sourceFilename, base.Request.MapPath(Globals.ApplicationPath + text9), 410, 410); if (index == 1) { product.ImageUrl1 = text; product.ThumbnailUrl40 = text2; product.ThumbnailUrl60 = text3; product.ThumbnailUrl100 = text4; product.ThumbnailUrl160 = text5; product.ThumbnailUrl180 = text6; product.ThumbnailUrl220 = text7; product.ThumbnailUrl310 = text8; product.ThumbnailUrl410 = text9; return; } switch (index) { case 2: product.ImageUrl2 = text; return; case 3: product.ImageUrl3 = text; return; case 4: product.ImageUrl4 = text; return; case 5: product.ImageUrl5 = text; return; default: return; } }
/// <summary> /// 文件备份 /// </summary> /// <param name="strSrcFilePath">原始文件路径</param> /// <returns>备份文件路径</returns> private void FileCopy(string strSrcFilePath, string strCopyPath) { System.IO.FileInfo fSrcFile = new System.IO.FileInfo(strSrcFilePath); System.IO.FileInfo fCopyFile = new System.IO.FileInfo(strCopyPath); fSrcFile.CopyTo(strCopyPath); }
public void Img_Load() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Image Files(*.jpg; .jpeg; .gif; .bmp)|*.jpg; .jpeg; .gif; .bmp"; openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (openFileDialog.ShowDialog() == true) { if (File.Exists(openFileDialog.FileName)) { IMAGE_PATH1 = new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute)); // IMAGE_PATH = Convert.ToString( new BitmapImage(new Uri(openFileDialog.FileName, UriKind.Absolute))); string imagepath = openFileDialog.FileName.ToString(); var imageFile = new System.IO.FileInfo(imagepath); string file = imageFile.Name; var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); // get your 'Uploaded' folder var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "uploaded")); if (!dir.Exists) { dir.Create(); } // Copy file to your folder imageFile.CopyTo(System.IO.Path.Combine(dir.FullName + "\\", file), true); string path1 = System.IO.Path.Combine(dir.FullName + "\\", file); Ftpup(path1, openFileDialog.SafeFileName); SelectedCompany.IMAGE_PATH = openFileDialog.SafeFileName; } } }
public void WriteLog(string sErrMsg) { try { string sFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog.txt"; System.IO.FileInfo objFileInfo = new System.IO.FileInfo(sFileName); if (!objFileInfo.Exists) objFileInfo.Create(); if (objFileInfo.Length > 10485760) { string str_number = Guid.NewGuid().ToString(); string newFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog\\" + str_number + "ErrorLog.txt"; objFileInfo.CopyTo(newFile); objFileInfo.Delete(); } string sPathName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "//ErrorLog.txt";//ConfigurationSettings.AppSettings["LogFileName"]; System.IO.FileStream objFileStream = objFileInfo.Open(System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objFileStream); objWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End); objWriter.WriteLine("Error Occured at " + DateTime.Now.ToLongDateString() + " : " + DateTime.Now.ToLongTimeString()); objWriter.WriteLine(sErrMsg); objWriter.WriteLine("----------------------------------------------------------------------"); objWriter.Close(); } catch { } }
public void TestBulkLoad24M() { var testTarget = new FileInfo(_importDirPath + Path.DirectorySeparatorChar + "BSBM_24M.nt"); if (!testTarget.Exists) { var testSource = new FileInfo("BSBM_24M.nt"); if (!testSource.Exists) { Assert.Inconclusive("Could not locate test source file {0}. Test will not run", testSource.FullName); return; } testSource.CopyTo(_importDirPath + Path.DirectorySeparatorChar + "BSBM_24M.nt"); } var timer = new Stopwatch(); timer.Start(); var bc = BrightstarService.GetClient("type=http;endpoint=http://localhost:8090/brightstar"); var storeName = Guid.NewGuid().ToString(); bc.CreateStore(storeName); var jobInfo = bc.StartImport(storeName, "BSBM_24M.nt", null); while (!jobInfo.JobCompletedOk) { Thread.Sleep(3000); jobInfo = bc.GetJobInfo(storeName, jobInfo.JobId); } timer.Stop(); Console.WriteLine("24M triples imported in {0} ms", timer.ElapsedMilliseconds); }
/// <summary> /// Updates the application's blocklist with the specified blocklist file. /// </summary> /// <param name="blocklistFile">The updated blocklist file.</param> public virtual void Update(FileInfo blocklistFile) { if (blocklistFile == null) throw new ArgumentNullException("blocklistFile"); if (TargetFile == null) throw new InvalidOperationException("The TargetFile is not set for the application"); blocklistFile.CopyTo(TargetFile.FullName, true); }
public string UploadFile(string file_local) { try { System.IO.FileInfo file = new System.IO.FileInfo(file_local); if (file.Exists) { string remote_path = host + "\\" + file.Name; using (new NetworkConnection(@host, new NetworkCredential(users, password))) { if (File.Exists(@remote_path)) { File.Delete(@remote_path); } file.CopyTo(@remote_path); } return(@remote_path); } } catch (Exception ex) { var _ex_ = ex; Messages.Exception(ex); } return(null); }
// Copy or overwrite destination file with source file. public static bool OverwriteFile(string srcFilePath, string destFilePath) { var fi = new System.IO.FileInfo(srcFilePath); if (!fi.Exists) { UnityEngine.Debug.LogError(string.Format("WwiseUnity: Failed to overwrite. Source is missing: {0}.", srcFilePath)); return(false); } var di = new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(destFilePath)); if (!di.Exists) { di.Create(); } const bool IsToOverwrite = true; try { fi.CopyTo(destFilePath, IsToOverwrite); } catch (Exception ex) { UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message)); return(false); } return(true); }
public static void Extend(FileInfo assembly, string type, DirectoryInfo javapath) { Console.WriteLine(new { javapath, type }); // http://social.msdn.microsoft.com/Forums/en-US/vbide/thread/0e946e63-a481-45b1-990d-af727914ff15 // in obj folder we build our binaries var obj = assembly.Directory.CreateSubdirectory("obj"); // in bin we copy what we consider as the product var bin = assembly.Directory.CreateSubdirectory("bin"); Environment.CurrentDirectory = obj.FullName; var obj_assembly = Path.Combine(obj.FullName, assembly.Name); assembly.CopyTo(obj_assembly, true); var ViaAssemblyBuilder_ExtensionPoint = new FileInfo(typeof(ViaAssemblyBuilder.ExtensionPoint.Definition).Assembly.Location); ViaAssemblyBuilder_ExtensionPoint.CopyTo(Path.Combine(obj.FullName, ViaAssemblyBuilder_ExtensionPoint.Name), true); var ScriptCoreLibA = new FileInfo(typeof(ScriptCoreLib.ScriptAttribute).Assembly.Location); ScriptCoreLibA.CopyTo(Path.Combine(obj.FullName, ScriptCoreLibA.Name), true); var ScriptCoreLibJava = new FileInfo(typeof(ScriptCoreLibJava.IAssemblyReferenceToken).Assembly.Location); ScriptCoreLibJava.CopyTo(Path.Combine(obj.FullName, ScriptCoreLibJava.Name), true); new MetaBuilder { obj = obj, bin = bin, javapath = javapath, assembly = Assembly.LoadFile(obj_assembly) }.Build(type); }
public async Task CopyToAsync(IFile destination, bool overwrite = true, bool createDirectory = true) { _ = destination ?? throw new ArgumentNullException(nameof(destination)); // Create the directory if (createDirectory) { IDirectory directory = destination.Directory; directory.Create(); } // Use the file system APIs if destination is also in the file system if (destination is LocalFile) { LocalFileProvider.RetryPolicy.Execute(() => _file.CopyTo(destination.Path.FullPath, overwrite)); } else { // Otherwise use streams to perform the copy using (Stream sourceStream = OpenRead()) { using (Stream destinationStream = destination.OpenWrite()) { await sourceStream.CopyToAsync(destinationStream); } } } }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "图片|*.jpg"; ofd.ValidateNames = true; ofd.CheckPathExists = true; ofd.CheckFileExists = true; if (ofd.ShowDialog() == DialogResult.OK) { file = new System.IO.FileInfo(ofd.FileName); //其他代码 pic.Text = ofd.FileName; destinationFile = @"\pic\" + file.Name; try { if (file.Exists) { file.CopyTo(System.Windows.Forms.Application.StartupPath + destinationFile, true); MessageBox.Show("图片更改成功"); } } catch { } } }
private static List<string> CheckFile(ConfigInfo config) { List<string> newFileNames = new List<string>(); foreach (var assInfo in config.AssemblyInfos) { string fileName = assInfo.FileName; FileInfo rFileinfo = new FileInfo(config.BaseUrl + fileName); FileInfo lFileInfo = new FileInfo(fileName); if (!rFileinfo.Exists) { try { File.Delete(assInfo.FileName); File.Delete(assInfo.FileName.ToUpper().Replace("ZIP", "DLL")); File.Delete(assInfo.FileName.Replace("ZIP", "EXE")); } catch (Exception ex) { } } if (!lFileInfo.Exists || lFileInfo.LastWriteTime < rFileinfo.LastWriteTime) { try { newFileNames.Add(assInfo.FileName); rFileinfo.CopyTo(assInfo.FileName, true); } catch (Exception ex) { } } } return newFileNames; }
public static bool CopyFile(string newFile, string oldFile) { var newfile = new FileInfo(newFile); var oldfile = new FileInfo(oldFile); string errorMsg = ""; var f2 = new FileIOPermission(FileIOPermissionAccess.AllAccess, oldFile); f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, newFile); try { f2.Demand(); } catch (SecurityException s) { Console.WriteLine(s.Message); } for (int x = 0; x < 100; x++) { try { File.Delete(oldfile.FullName); newfile.CopyTo(oldfile.FullName, true); return true; } catch(Exception e) { errorMsg = e.Message + " : " + e.InnerException; Thread.Sleep(200); } } Data.Logger(errorMsg); return false; }
private static void LosslessCompress(FileInfo file, bool progressive) { FileInfo output = new FileInfo(Path.GetTempFileName()); try { int result = NativeJpegOptimizer.Optimize(file.FullName, output.FullName, progressive); if (result == 1) throw new MagickCorruptImageErrorException("Unable to decompress the jpeg file.", null); if (result == 2) throw new MagickCorruptImageErrorException("Unable to compress the jpeg file.", null); if (result != 0) return; output.Refresh(); if (output.Length < file.Length) output.CopyTo(file.FullName, true); file.Refresh(); } finally { FileHelper.Delete(output); } }
private void Sign(string filename) { try { string p = @"<RSAKeyValue><Modulus>wJqUfZ3Iry4fV6p1bjO817u2/HE1zCmsnguE0Of+1Dzzcc+L3psx1PsDmXlxcLU9E4+ndbIacC2XMWlrIaLSikIJgfMwuvBej18HrrNATpKHwprUpRMU3P9ug5iemz0pyHA3Nr+keCU/b/HsFmido6R1cuBSDd6RYtlK1Xx+KlU=</Modulus><Exponent>AQAB</Exponent><P>+37HaPakQZN5GKh7Jf8a4b/3kqHIynsd0CYVNN0ax3qqRneEdyhfC2CzJGjv6UPOyAXZHn/T8kWpcSfLbqMlqw==</P><Q>xA3Byhq3RTP4YJYBdri/AZMBpRTiV+xSKi1XLz9m0QsNE5ctuwhbD3wY3YlMdIAbOAVewrxjTJg336z2JHPv/w==</Q><DP>VPgKa14ZNMacfUY/BSFhdbAj9viOHEroUbDsLUYejBLXgKNUr+WF5xQusjh6BfeQ32eKaZGKjCoZC1AEnUalrQ==</DP><DQ>BDAnC6I2eAv8KlQKA/c+XVI+nsArdaVeu/fr/N5l2+FYjiqUl4I+L75+6XydXX+/FRtIQvCzTleSGf0f5Pd1EQ==</DQ><InverseQ>xwGNcideNnj6XrDwLFSv3y7CMq2vMzuYxaObaNTU9sh1PTKVMRpiwdKWKpwnstXmDaSduBVw4EvfNlaz+SzUuw==</InverseQ><D>AJc4x13ZhLgGfpVWQN1Fwf+gYwvR12t1TRLJ+H4NqQb61CmHy0n8kCOo8iqOL4NOyaWSJOlD7X4mTY9+NZ8zOBn2Wij0r606Omw+/rlU986lwcxdBiw3y/LND3gowf1gR3Ei9K0eYsHTZZ9Ry9pmqowXi1DG916MBWSuwAbiOw0=</D></RSAKeyValue>"; RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(p); FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None); SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider(); byte[] hash = sha1.ComputeHash(fs); byte[] b = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")); fs.Close(); FileInfo fi = new FileInfo(filename); fi.CopyTo(filename + ".p1s", true); FileStream fo = new FileStream(filename + ".p1s", FileMode.Append, FileAccess.Write, FileShare.None); fo.Write(b, 0, b.Length); fo.Close(); MessageBox.Show(filename + ".p1s is successfully created."); } catch (Exception e) { MessageBox.Show(e.ToString()); } }
private void addFile_Click(object sender, EventArgs e) { Guid newNameId = Guid.NewGuid(); OpenFileDialog openFileDlg = new OpenFileDialog(); // TODO Save new files position to user settings. openFileDlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (openFileDlg.ShowDialog() == DialogResult.OK) { FileInfo fileInfo = new FileInfo(openFileDlg.FileName); if (fileInfo.Length / 1024 < viewModel.SizeLimit) { if (!Directory.Exists(Directories.FilesToAttachFolder)) { Directory.CreateDirectory(Directories.FilesToAttachFolder); DirectoryInfo directoryInfo = new DirectoryInfo(Directories.FilesToAttachFolder); DirectoryInfo directoryInfoParent = new DirectoryInfo(Directories.TargetPath); directoryInfo.Attributes |= FileAttributes.Hidden; directoryInfoParent.Attributes |= FileAttributes.Hidden; } string filesToAttachPath = string.Format("{0}{1}{2}", Directories.FilesToAttachFolder, newNameId, fileInfo.Extension); fileInfo.CopyTo(filesToAttachPath); viewModel.FilesToAttach.Add(newNameId.ToString() + fileInfo.Extension, fileInfo.Name); Prizm.Domain.Entity.File newFile = new Prizm.Domain.Entity.File() { FileName = fileInfo.Name, UploadDate = DateTime.Now }; newFile.NewName = filesToAttachPath; viewModel.Files.Add(newFile); } else { XtraMessageBox.Show(Program.LanguageManager.GetString(StringResources.ExternalFiles_FileSizeIsTooBig), Program.LanguageManager.GetString(StringResources.Message_ErrorHeader)); } } }
public override void executeTest( ) { Console.WriteLine("Test Case: Change Encoding of the xml file to UTF -7"); try { string holodeckPath; holodeckPath = (string) Registry.LocalMachine.OpenSubKey ("Software\\HolodeckEE", true).GetValue ("InstallPath"); FunctionsXMLFilePath = string.Concat(holodeckPath,"\\function_db\\functions.xml"); FunctionsXMLBackupFilePath = string.Concat(FunctionsXMLFilePath,".bak"); modifyThisFile = new FileInfo(FunctionsXMLFilePath); modifyThisFile.Attributes = FileAttributes.Normal; modifyThisFile.CopyTo(FunctionsXMLBackupFilePath); //modify xml here FunctionXMLNavigator FuncXMLNav = new FunctionXMLNavigator(); FunctionsXMLFilePath = modifyThisFile.FullName; FuncXMLNav.ValidateXmlDocument(FunctionsXMLFilePath); FuncXMLNav.parseXmlDocument(FunctionsXMLFilePath); //saving the functions.xml FuncXMLNav.saveFunctionXmlDocument(FuncXMLNav,FunctionsXMLFilePath,"UTF-7",true); try { //add code here which will launch Holodeck Holodeck.HolodeckProcess.Start(); } catch(Holodeck.HolodeckExceptions.CannotStartHolodeckException ex) { Console.WriteLine("Cannot Start Holodeck Exception thrown "); Console.WriteLine(ex.Message); } } catch(HolodeckExceptions.IncorrectRegistryException e) { Console.WriteLine(" Incorrect Registry Exception caught.... : " + e.Message); Console.WriteLine("Details: " + e.StackTrace); } catch(FileNotFoundException f) { Console.WriteLine(" File Not Found Exception caught.... : " + f.Message); Console.WriteLine("Details: " + f.StackTrace); } finally { if(Holodeck.HolodeckProcess.IsRunning ()) { Holodeck.HolodeckProcess.Stop(); } //reverting back to original modifyThisFile.Delete(); FileInfo regainOriginal = new FileInfo(FunctionsXMLBackupFilePath); regainOriginal.MoveTo(FunctionsXMLFilePath); } }
private static void CopyAssets(string source, string target) { if (!Directory.Exists(target)) { Directory.CreateDirectory(target); } foreach (var filename in Directory.GetFiles(source)) { var file = new System.IO.FileInfo(filename); file.CopyTo(Path.Combine(target, file.Name), true); if (file.Name.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase)) { var contents = File.ReadAllText(file.FullName); while (contents.Contains("\r ")) { contents = contents.Replace("\r ", "\r"); } while (contents.Contains("\n ")) { contents = contents.Replace("\n ", "\n"); } contents = contents.Replace("\r", ""); contents = contents.Replace("\n", ""); File.WriteAllText(file.FullName, contents); } } }
private static void CopyDirectoryStructure(string SourcePath, string DestinationPath, bool overwriteexisting) { try { SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; if (Directory.Exists(SourcePath)) { if (Directory.Exists(DestinationPath) == false) Directory.CreateDirectory(DestinationPath); foreach (string fls in Directory.GetFiles(SourcePath)) { FileInfo flinfo = new FileInfo(fls); //resize the file flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } foreach (string drs in Directory.GetDirectories(SourcePath)) { DirectoryInfo diDi = new DirectoryInfo(drs); CopyDirectoryStructure(drs, DestinationPath + diDi.Name, overwriteexisting); } } } catch (Exception ex) { } }
public override void executeTest( ) { Console.WriteLine("Test Case: Make Functions.xml with only <Functions> tag"); try { string holodeckPath; holodeckPath = (string) Registry.LocalMachine.OpenSubKey ("Software\\HolodeckEE", true).GetValue ("InstallPath"); FunctionsXMLFilePath = string.Concat(holodeckPath,"\\function_db\\functions.xml"); FunctionsXMLBackupFilePath = string.Concat(FunctionsXMLFilePath,".bak"); modifyThisFile = new FileInfo(FunctionsXMLFilePath); modifyThisFile.Attributes = FileAttributes.Normal; modifyThisFile.CopyTo(FunctionsXMLBackupFilePath); //modify xml here FunctionsXMLFilePath = modifyThisFile.FullName; XmlDocument xmlDocument = new XmlDocument( ); xmlDocument.Load(FunctionsXMLFilePath); XmlNode node = xmlDocument.SelectSingleNode( "/Functions" ); node.RemoveAll(); xmlDocument.Save(FunctionsXMLFilePath); try { //add code here which will launch Holodeck Holodeck.HolodeckProcess.Start(); } catch(Holodeck.HolodeckExceptions.CannotStartHolodeckException ex) { Console.WriteLine("Cannot Start Holodeck Exception thrown "); Console.WriteLine(ex.Message); } } catch(HolodeckExceptions.IncorrectRegistryException e) { Console.WriteLine(" Incorrect Registry Exception caught.... : " + e.Message); Console.WriteLine("Details: " + e.StackTrace); } catch(FileNotFoundException f) { Console.WriteLine(" File Not Found Exception caught.... : " + f.Message); Console.WriteLine("Details: " + f.StackTrace); } finally { if(Holodeck.HolodeckProcess.IsRunning ()) { Holodeck.HolodeckProcess.Stop(); } //reverting back to original modifyThisFile.Delete(); FileInfo regainOriginal = new FileInfo(FunctionsXMLBackupFilePath); regainOriginal.MoveTo(FunctionsXMLFilePath); } }
public static bool CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting) { bool ret = false; try { SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\"; DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\"; if (Directory.Exists(SourcePath)) { if (Directory.Exists(DestinationPath) == false) Directory.CreateDirectory(DestinationPath); foreach (string fls in Directory.GetFiles(SourcePath)) { FileInfo flinfo = new FileInfo(fls); flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting); } foreach (string drs in Directory.GetDirectories(SourcePath)) { DirectoryInfo drinfo = new DirectoryInfo(drs); if (CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting) == false) ret = false; } } ret = true; } catch (Exception ex) { ret = false; } return ret; }
public static bool WriteFile(IRaiseEvent bh, int t, FileInfo fileInfo, byte[] buffer, bool rename) { try { if (fileInfo.Exists) { if (rename) { DateTime td = DateTime.Now; int index = fileInfo.FullName.LastIndexOf('.'); string newName = fileInfo.FullName.Remove(index, fileInfo.FullName.Length - index); newName = newName + td.ToString("MMddHHmmss") + ".txt"; fileInfo.CopyTo(newName); } else { fileInfo.Delete(); } } FileReadWriteState ws = new FileReadWriteState(bh, t, fileInfo); ws.MFileStream = new FileStream(fileInfo.FullName, FileMode.Create, FileAccess.Write, FileShare.None, BufferSize, true); IAsyncResult asyncResult = ws.MFileStream.BeginWrite( buffer, 0, buffer.Length, new AsyncCallback(WriteFileComplete), ws); } catch (Exception e) { FileReadWriteState st = new FileReadWriteState(bh, t, fileInfo); st.RaiseException(e); } return true; }
public void CopyFile(string path, string namefile) { try { fil = new FileInfo(path); Console.ForegroundColor = ConsoleColor.Red; Console.Write("Enter new path for copy: "); Console.ForegroundColor = ConsoleColor.White; string newPath = Console.ReadLine() + "\\" + namefile; Console.WriteLine(newPath); if (fil.Exists && Directory.Exists(newPath) == false) { fil.CopyTo(newPath,true); Console.WriteLine("File copied"); } else { Console.WriteLine("Error!!"); } } catch (Exception) { throw; } }
public static bool CopyDirectory(string sourcePath, string destinationPath, bool overwriteexisting) { bool ret = false; try { sourcePath = sourcePath.EndsWith(@"\") ? sourcePath : sourcePath + @"\"; destinationPath = destinationPath.EndsWith(@"\") ? destinationPath : destinationPath + @"\"; if (IsExistDirectory(sourcePath)) { if (IsExistDirectory(destinationPath) == false) Directory.CreateDirectory(destinationPath); foreach (string fls in Directory.GetFiles(sourcePath)) { FileInfo flinfo = new FileInfo(fls); flinfo.CopyTo(destinationPath + flinfo.Name, overwriteexisting); } foreach (string drs in Directory.GetDirectories(sourcePath)) { DirectoryInfo drinfo = new DirectoryInfo(drs); if (CopyDirectory(drs, destinationPath + drinfo.Name, overwriteexisting) == false) ret = false; } } ret = true; } catch (Exception ex) { CooperationWrapper.WriteLog(ex); ret = false; } return ret; }
private void processStudies(string parentDir) { DicomUpdate dicomUpdate = new DicomUpdate(); foreach (string dirs in Directory.GetDirectories(parentDir)) { string dirName = Path.GetFileName(dirs); string targetOutputDirectory = _targetDir + "\\New_" + dirName; Directory.CreateDirectory(targetOutputDirectory); foreach (string file in Directory.GetFiles(dirs, "*", SearchOption.AllDirectories)) { FileInfo fileInfo = new FileInfo(file); toolstripStatuslbl.Text = "Copying file " + fileInfo.Name; if (fileInfo.Extension == ".dcm") { fileInfo.CopyTo(targetOutputDirectory + "\\" + fileInfo.Name, true); } } toolstripStatuslbl.Text = "Creating Update Objects"; List<UpdateData> updateObjects = generateUpdateObjectList(targetOutputDirectory); foreach (UpdateData update in updateObjects) { toolstripStatuslbl.Text = "Should be updating now..."; dicomUpdate.UpdateDicomFile(update); } } toolstripStatuslbl.Text = "Done"; }
private void btnchon_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "file hinh|*.jpg|all file|*.*"; dlg.InitialDirectory = @"E:\"; dlg.Multiselect = true; if (dlg.ShowDialog() == DialogResult.OK) { string[] tmp = dlg.FileNames; foreach (string i in tmp) { FileInfo fi = new FileInfo(i); string[] xxx = i.Split('\\'); string des = @"../../../MVCShop/Content/ImageSP/" + xxx[xxx.Length - 1]; File.Delete(des); //over. fi.CopyTo(des); txtha.Text = ""; txtha.Text = des; //MessageBox.Show("Chọn hình ảnh thành công"); pichinhanh.Image = Image.FromFile(des); _hinh = Path.GetFileName(des); } } }
public override void executeTest( ) { Console.WriteLine("Test Case :Make Faults.xml with Faults Fault ErrorCode Value Edited to \"originalValue + testValue\""); try { string holodeckPath; holodeckPath = (string) Registry.LocalMachine.OpenSubKey ("Software\\HolodeckEE", true).GetValue ("InstallPath"); FaultsXMLFilePath = string.Concat(holodeckPath,"\\function_db\\faults.xml"); FaultsXMLBackupFilePath = string.Concat(FaultsXMLFilePath,".bak"); modifyThisFile = new FileInfo(FaultsXMLFilePath); modifyThisFile.Attributes = FileAttributes.Normal; modifyThisFile.CopyTo(FaultsXMLBackupFilePath,true); //modify xml here FaultsXMLFilePath = modifyThisFile.FullName; XmlDocument xmlDocument = new XmlDocument( ); xmlDocument.Load(FaultsXMLFilePath); XmlNode nodeFault = xmlDocument.SelectSingleNode( "/Faults/Fault[@ErrorCode]" ); EditValues editFalutReturnValue = new EditValues(); editFalutReturnValue.EditFault(nodeFault,testValue,"ErrorCode"); Console.WriteLine("Editing Fault ErrorCode Attribute of {0} fault to {1}",nodeFault.Attributes["Name"].Value.ToString(),nodeFault.Attributes["ErrorCode"].Value.ToString()); xmlDocument.Save(FaultsXMLFilePath); //add code here which will launch Holodeck Holodeck.HolodeckProcess.Start(); } catch(HolodeckExceptions.IncorrectRegistryException e) { Console.WriteLine(" Incorrect Registry Exception caught.... : " + e.Message); Console.WriteLine("Details: " + e.StackTrace); } catch(FileNotFoundException f) { Console.WriteLine(" File Not Found Exception caught.... : " + f.Message); Console.WriteLine("Details: " + f.StackTrace); } finally { if(Holodeck.HolodeckProcess.IsRunning ()) { Holodeck.HolodeckProcess.Stop(); } //reverting back to original modifyThisFile.Delete(); FileInfo regainOriginal = new FileInfo(FaultsXMLBackupFilePath); regainOriginal.MoveTo(FaultsXMLFilePath); } }
public void WriteLog(string Msg) { DateTime t = DateTime.Now; FileInfo f = new FileInfo(_logFullName); StreamWriter S; if (!f.Exists) { S = File.AppendText(_logFullName); } else if (f.Length >= MAX_LOG_SIZE) { f.CopyTo(_logFullName+".bak"); S = File.CreateText(_logFullName); } else { S = File.AppendText(_logFullName); } S.WriteLine(t.ToShortDateString() + "," + t.ToLongTimeString() + " : " + Msg); System.Diagnostics.Debug.WriteLine(Msg); S.Close(); try { if (m_ctlInvokeTarget != null) { strBuffer = Msg; m_ctlInvokeTarget.Invoke(m_deleCallback); } } catch (Exception) { } }
public FileInfo CreateTestFileAndCopyToFolder(string pathToCopyTo) { string path = Path.GetTempFileName(); FileInfo fi1 = new FileInfo(path); //Create a file to write to. using (StreamWriter sw = fi1.CreateText()) { sw.WriteLine("Title"); sw.WriteLine("Lots of happenings"); sw.WriteLine("Bazinga"); } try { //Copy the file. fi1.CopyTo(pathToCopyTo+"\\TempFile.txt"); FileInfo fi2 = new FileInfo(pathToCopyTo + "\\TempFile.txt"); return fi2; } catch (Exception e) { Console.WriteLine("The process failed: {0}", e.ToString()); } return null; }
public static string CopyFile(FileInfo file) { string newFileName = PathBoss.ExtractPath() + file.Name + "_" + DateTime.Now.ToString("hhmmssfff") + "." + file.Extension; if (!File.Exists(newFileName)) file.CopyTo(newFileName, true); return newFileName; }
private static void BackupGame(Game game, string destDirName) { Debug.WriteLine(@"Starting file copy for " + game.Name); var allFiles = Directory.GetFiles(game.Path, "*.*", SearchOption.AllDirectories); foreach (var sourceFile in allFiles) { try { var index = sourceFile.IndexOf(game.RootFolder, StringComparison.CurrentCulture); var substring = sourceFile.Substring(index); var destinationFi = new FileInfo(destDirName + "\\" + substring); var destinationDir = destinationFi.DirectoryName; if (!Directory.Exists(destinationDir)) Directory.CreateDirectory(destinationDir); var file = new FileInfo(sourceFile); file.CopyTo(destinationFi.FullName, true); _progress.FilesComplete++; Messenger.Default.Send(_progress); } catch (IOException ex) { SBTErrorLogger.Log(ex.Message); } catch (NullReferenceException ex) { SBTErrorLogger.Log(ex.Message); } } Debug.WriteLine(@"Finished file copy for " + game.Name); }
private void BackgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { try { var nOfFiles = fileToCopy.Count; backgroundWorker2.ReportProgress(-1, nOfFiles); var index = 0; result.Clear(); foreach (string item in fileToCopy) { index++; if (string.IsNullOrEmpty(item)) { continue; } var fi = new System.IO.FileInfo(item); if (fi.Exists) { //var source = directory1 + System.IO.Path.DirectorySeparatorChar + fi.Name; //result.Add(source, source); var target = directory2 + System.IO.Path.DirectorySeparatorChar + fi.Name; result.Add(target, target); fi.CopyTo(target); var previouslyHashedFiles = GetHashedFiles(directory2); var matchPair = infoList1.FirstOrDefault(x => x.Value == fi.FullName); if (!string.IsNullOrEmpty(matchPair.Key)) { UpdateHashFile(matchPair.Key, fi.FullName, directory2 + Path.DirectorySeparatorChar, previouslyHashedFiles); } else { var error = new Exception(string.Format("Match pair error: {0}, {1}", matchPair.ToString(), fi.FullName)); exception = error; throw exception; } } backgroundWorker2.ReportProgress(index); } } catch (Exception ex) { exception = ex; } }
private static void AutoBackUp() { Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string From = ConfigurationManager.AppSettings["FromPath"].ToString(); string[] Fromarray = From.Split(';'); string ToDirectory = ConfigurationManager.AppSettings["ToPath"].ToString() + System.DateTime.Now.ToString("yyyyMMddHH") + "\\"; string logpath = Application.StartupPath + "\\log_" + System.DateTime.Now.ToString("yyyyMMdd") + ".txt"; string WriteWord = ""; string Filter = ConfigurationManager.AppSettings["ext"]; //建立備份目的資料夾 if (!Directory.Exists(ToDirectory)) { Directory.CreateDirectory(ToDirectory); } //建立Log檔 if (!File.Exists(logpath)) { File.Create(logpath).Close(); } try { for (int i = 0; i < Fromarray.Length; i++) { string FromDirectory = Fromarray[i]; string[] patterns = Filter.Split('|'); foreach (string pt in patterns) { string[] FileList = System.IO.Directory.GetFiles(FromDirectory, pt); foreach (string File in FileList) { System.IO.FileInfo fi = new System.IO.FileInfo(File); fi.CopyTo(ToDirectory + fi.Name, true); WriteWord += System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff") + "\t" + fi.Name + "\t\t已成功備份至" + ToDirectory + "\r\n"; } } } } catch (Exception ex) { WriteWord += System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff") + "\t發生錯誤!!\r\n"; } using (FileStream fs = new FileStream(logpath, FileMode.Append)) { using (StreamWriter writer = new StreamWriter(fs)) { writer.WriteLine(WriteWord); } } }
public async void Document_Upload() { string ProductCode = App.Current.Properties["Product_Code"].ToString(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); if (openFileDialog.ShowDialog() == true) { if (File.Exists(openFileDialog.FileName)) { string docfilepath = openFileDialog.FileName.ToString(); var docFile = new System.IO.FileInfo(docfilepath); string file = docFile.Name; var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); // get your 'Uploaded' folder var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "uploaded")); if (!dir.Exists) { dir.Create(); } // Copy file to your folder docFile.CopyTo(System.IO.Path.Combine(dir.FullName + "\\", file), true); //Prepare Document Model DocumentModel doc = new DocumentModel(); doc.FILE_NAME = file; doc.TYPE_ID_DOC = docFile.Extension; doc.SIZE = docFile.Length.ToString() + " bytes"; doc.DATE = docFile.LastWriteTime.ToString(); doc.PRODUCT_CODE = ProductCode; //Insert data try { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.BaseAddress = new Uri(GlobalData.gblApiAdress); var response = await client.PostAsJsonAsync("api/DocumentAPI/CreateProductDocument/", doc); ////// //Refresh List } catch (Exception) { throw; } GetDocuments(ProductCode); } } }
public static void copy(string sourceFilePath, string targetFilePath) { FileInfo sourceFileInfo = new System.IO.FileInfo(sourceFilePath); if (!sourceFileInfo.Exists) { return; } sourceFileInfo.CopyTo(targetFilePath, true); }
public ActionResult UploadPostImageEdit(HttpPostedFileBase file, int post_id) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { if (file != null && file.ContentLength > 0) { hypster_tv_DAL.newsManagement_Admin newsManager = new hypster_tv_DAL.newsManagement_Admin(); hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); hypster_tv_DAL.newsPost p_Post = new hypster_tv_DAL.newsPost(); p_Post = newsManager.GetPostByID(post_id); var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_post" + extension); file.SaveAs(path); //save post image System.IO.FileInfo fileInf = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); fileInf.CopyTo(System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\" + p_Post.post_guid + fileInf.Extension, true); // // resize image old int video_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postImage_maxWidth"]); image_resizer.Resize_Image(System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\" + p_Post.post_guid + fileInf.Extension, video_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //save thumbnail System.IO.FileInfo thumb_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); string new_thumb_path = System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\thumb_" + p_Post.post_guid + thumb_file.Extension; thumb_file.CopyTo(new_thumb_path, true); int thumb_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postThumb_maxWidth"]); image_resizer.Resize_Image(new_thumb_path, thumb_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //save new image System.IO.FileInfo newim_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); string newim_path = System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\img_" + p_Post.post_guid + newim_file.Extension; newim_file.CopyTo(newim_path, true); int newim_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["newPostImage_maxWidth"]); image_resizer.Resize_Image(newim_path, newim_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); del_file.Delete(); p_Post.post_image = p_Post.post_guid + fileInf.Extension; // // save post after image is done newsManager.EditPost(p_Post); } return(RedirectToAction("Edit", new { id = post_id })); } else { return(RedirectPermanent("/home/")); } }
/// <summary> /// 拷贝文件到目标目录。 /// </summary> /// <param name="files">文件路径</param> /// <param name="desPath">目标文件夹路径</param> public static void CopyFiles(System.IO.FileInfo files, System.IO.DirectoryInfo desPath) { if (!files.Exists) { return; } var newfilePath = Path.Combine(desPath.FullName, files.Name); files.CopyTo(newfilePath, true); }
public void SaveSettings() { UpdateTimer.Stop(); // Save settigns to INI file. SettingManager.Current.SaveSettings(); // Owerwrite Temp file. var ini = new System.IO.FileInfo(SettingManager.IniFileName); ini.CopyTo(SettingManager.TmpFileName, true); StatusTimerLabel.Text = "Settings saved"; UpdateTimer.Start(); }
private void moveFileIfExists(string file, DirectoryInfo destination) { if (!storage.Exists(file)) { return; } Logger.Log($"Migrating {file} to default tournament storage."); var fileInfo = new System.IO.FileInfo(storage.GetFullPath(file)); AttemptOperation(() => fileInfo.CopyTo(Path.Combine(destination.FullName, fileInfo.Name), true)); fileInfo.Delete(); }
public void UploadImage(HttpPostedFileBase file, int id) { if (file != null && file.ContentLength > 0) { newsPost p_Post = new newsPost(); newsManagement_Admin newsManager = new newsManagement_Admin(); Image_Resize_Manager image_resizer = new Image_Resize_Manager(); p_Post = newsManager.GetPostByID(id); var extension = System.IO.Path.GetExtension(file.FileName); if (file.FileName != "") { var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_post" + extension); file.SaveAs(path); //save post image System.IO.FileInfo fileInf = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); fileInf.CopyTo(System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\" + p_Post.post_guid + fileInf.Extension, true); // // resize image old int video_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postImage_maxWidth"]); image_resizer.Resize_Image(System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\" + p_Post.post_guid + fileInf.Extension, video_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //save thumbnail System.IO.FileInfo thumb_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); string new_thumb_path = System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\thumb_" + p_Post.post_guid + thumb_file.Extension; thumb_file.CopyTo(new_thumb_path, true); int thumb_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postThumb_maxWidth"]); image_resizer.Resize_Image(new_thumb_path, thumb_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //save new image System.IO.FileInfo newim_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); string newim_path = System.Configuration.ConfigurationManager.AppSettings["newsImageStorage_Path"] + "\\img_" + p_Post.post_guid + newim_file.Extension; newim_file.CopyTo(newim_path, true); int newim_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["newPostImage_maxWidth"]); image_resizer.Resize_Image(newim_path, newim_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); del_file.Delete(); p_Post.post_image = p_Post.post_guid + fileInf.Extension; // // save post after image is done newsManager.EditPost(p_Post); } } }
private void GenerateContent() { try { sb = new StringBuilder(); sb.AppendLine("--Generated Upgrade For Version " + _model.Version + "." + this.GetNextGeneratedVersion()); sb.AppendLine("--Generated on " + DateTime.Now.ToString("yyy-MM-dd HH:mm:ss")); sb.AppendLine(); //*********************************************************** //ATTEMPT TO GENERATE AN UPGRADE SCRIPT FROM PREVIOUS VERSION //*********************************************************** #region Generate Upgrade Script //Find the previous model file if one exists string fileName = this._model.GeneratorProject.FileName; System.IO.FileInfo fi = new System.IO.FileInfo(fileName); if (fi.Exists) { fileName = fi.Name + ".lastgen"; fileName = System.IO.Path.Combine(fi.DirectoryName, fileName); fi = new System.IO.FileInfo(fileName); if (fi.Exists) { //Load the previous model Widgetsphere.Generator.Common.GeneratorFramework.IGenerator generator = Widgetsphere.Generator.Common.GeneratorFramework.GeneratorHelper.OpenModel(fi.FullName); ModelRoot oldRoot = (ModelRoot)generator.RootController.Object; sb.Append(DatabaseHelper.GetModelDifferenceSQL(oldRoot, _model)); //Copy the current LASTGEN file to BACKUP fi.CopyTo(fileName + ".bak", true); } //Save this version on top of the old version System.IO.FileInfo currentFile = new System.IO.FileInfo(this._model.GeneratorProject.FileName); currentFile.CopyTo(fileName, true); } #endregion } catch (Exception ex) { throw; } }
private void copylog() //ログをSkypeのとこから手元にコピペ { string skypeID = Properties.Settings.Default.SkypeID; //DB探すのにIDいる&設定から持ってくる try //エラー発生する可能性あり { //ファイルの場所 System.IO.FileInfo fi = new System.IO.FileInfo(@System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Skype\\" + skypeID + "\\Main.db"); //手元にコピー System.IO.FileInfo copyFile = fi.CopyTo(@"main.db", true); } catch (Exception ex)//エラー出たら { //表示 MessageBox.Show(ex.Message, "ファイル探査エラー"); } }
public bool InitREDatabase(int epsgCode, ProjectLoadingView loadingForm, out string errorMsg) { errorMsg = ""; if (string.IsNullOrEmpty(_databaseName)) { errorMsg = "没有设置数据库!"; return false; } _epsgCode = epsgCode; FileInfo info = new FileInfo(_databaseName); if (!info.Exists) { loadingForm.ShowProgress(60,"创建数据库"); System.IO.FileInfo tmpFileInfo = SQLiteHelpers.GetTemplateDBInfo(); tmpFileInfo.CopyTo(_databaseName); } using (SQLiteConnection connection = new SQLiteConnection(SQLiteHelpers.ConnectionStringBuilder(_databaseName))) { connection.Open(); SpatialiteSharp.SpatialiteLoader.Load(connection); loadingForm.ShowProgress(70, "创建系统表"); CreateRESystemTables(connection); loadingForm.ShowProgress(70, "创建数据字典"); ImportDictionary(connection); loadingForm.ShowProgress(80, "创建地籍表"); CreateREZDTables(connection); loadingForm.ShowProgress(90, "创建居民地底图表"); CreateREBasemapTables(connection,"JMD"); loadingForm.ShowProgress(92, "创建道路底图表"); CreateREBasemapTables(connection, "DL"); loadingForm.ShowProgress(93, "创建水系底图表"); CreateREBasemapTables(connection, "SX"); loadingForm.ShowProgress(94, "创建地貌底图表"); CreateREBasemapTables(connection, "DMTZ"); loadingForm.ShowProgress(95, "创建独立地物底图表"); CreateREBasemapTables(connection, "DLDW"); loadingForm.ShowProgress(96, "创建其他底图表"); CreateREBasemapTables(connection, "QT"); loadingForm.ShowProgress(97, "创建注记底图表"); CreateREBasemapTables(connection, "ZJ",true,true,false,true); loadingForm.ShowProgress(90, "创建临时表"); CreateRECADTempTables(connection); } return true; }
/// <summary> /// Descomprime el archivo especificado en el directorio correspondiente /// </summary> /// <param name="fi"></param> public static string decompressFile(FileInfo fi) { string name = fi.Name.ToString().Replace(".pkg", ""); FileInfo zipfile = fi.CopyTo(name + ".zip" ,true); string dirDestino = fi.Directory.FullName + @"\" + name; if(Directory.Exists(dirDestino)==true) { Directory.Delete(dirDestino,true); } Directory.CreateDirectory(dirDestino); fi.Delete(); Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipfile.FullName); zf.ExtractAll(dirDestino,Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); Console.WriteLine("extraido aunque no lo parezca"); return dirDestino; /* using (FileStream infile = fi.OpenRead()) { string curfile = fi.FullName; string originalName = curfile.Remove(curfile.Length - fi.Extension.Length); using (FileStream outfile = File.Create(originalName)) { using (GZipStream decompress = new GZipStream(infile, CompressionMode.Decompress)) { decompress.CopyTo(outfile); } } } */ }