protected void btnUpload_Click(object sender, EventArgs e) { //备份原来的文件,保存新上传的文件并重命名 if (!file1.HasFile) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('请选择导入的文件')", true); return; } else if (!file1.FileName.EndsWith(".xls")) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "alert('请选择一个Excel文件')", true); return; } string filePath = Server.MapPath("~/") + @"uploads\teacherInfo\"; string fileName = "科研人事行政各类成果汇编"; System.IO.FileInfo fi = new System.IO.FileInfo(filePath + fileName + ".xls"); if (fi.Exists) { fi.CopyTo(filePath + fileName + "_bak" + DateTime.Now.ToString("yyyy年MM月dd日hh时mm分") + ".xls"); fi.Delete(); } file1.SaveAs(filePath + fileName + ".xls"); sys.alert("保存成功!"); }
/// <summary> /// Check and duplicate the single slide ppt /// Copy to the destination /// </summary> /// <param name="origin"></param> /// <param name="target"></param> public void CheckCopySlides(string origin, string target) { POWERPOINT.ApplicationClass ppt = new POWERPOINT.ApplicationClass(); POWERPOINT.Presentation pres = ppt.Presentations.Open( origin, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse); if (pres.Slides.Count == 1) { pres.SaveAs( target, POWERPOINT.PpSaveAsFileType.ppSaveAsDefault, Microsoft.Office.Core.MsoTriState.msoCTrue); pres.Slides[1].Copy(); pres.Slides.Paste(2); pres.Save(); } else { System.IO.FileInfo file = new System.IO.FileInfo(origin); file.CopyTo(target, true); } pres.Close(); ppt.Quit(); }
public ActionResult Edit(HttpPostedFileBase file, hypster_tv_DAL.videoFeaturedSlideshow featuredVideo) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { if (file != null && file.ContentLength > 0) { var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_featured_slide" + extension); file.SaveAs(path); string image_guid = featuredVideo.ImageSrc; // // resize image // hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); image_resizer.Resize_Image(path, 621, 376, System.Drawing.Imaging.ImageFormat.Jpeg); System.IO.FileInfo file_slide = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_featured_slide" + extension); file_slide.CopyTo(System.Configuration.ConfigurationManager.AppSettings["videoSlideshowStorage_Path"] + "\\" + image_guid, true); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_featured_slide" + extension); del_file.Delete(); } return(RedirectToAction("Index")); } else { return(RedirectPermanent("/home/")); } }
public void TestMethod1() { if (System.IO.File.Exists("TOTO.txt")) { System.IO.File.GetCreationTime("toto.txt"); System.IO.File.Copy("toto.txt", "titi.txt"); System.IO.File.Move("toto.txt", "tata.txt"); System.IO.File.CreateText("nouveauFichier.txt"); } System.IO.FileInfo oFileInfo = new System.IO.FileInfo("TOTO.txt"); if (oFileInfo.Exists) { Console.Write(oFileInfo.CreationTime); Console.Write(oFileInfo.LastAccessTime); Console.Write(oFileInfo.LastWriteTime); Console.Write(oFileInfo.Length); Console.Write(oFileInfo.Extension); Console.Write(oFileInfo.Name); Console.Write(oFileInfo.FullName); oFileInfo.CopyTo("titi.txt"); oFileInfo.MoveTo("tata.txt"); oFileInfo.CreateText(); } String[] tab = System.IO.Directory.GetFiles("c:\temp"); List <String> olst = new List <string>(System.IO.Directory.EnumerateFiles("c:\temp")); String[] tabD = System.IO.Directory.GetDirectories("c:\temp"); List <String> olstD = new List <string>(System.IO.Directory.EnumerateDirectories("c:\temp")); }
// 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 (System.Exception ex) { UnityEngine.Debug.LogError(string.Format("WwiseUnity: Error during installation: {0}.", ex.Message)); return(false); } return(true); }
/// <summary> /// 复制 JSON 文件 /// </summary> /// <param name="path"></param> /// <param name="fileName"></param> private void copyDotNetCoreJson(string path, string fileName) { System.IO.FileInfo file = new System.IO.FileInfo(AutoCSer.Config.ApplicationPath + fileName); if (file.Exists) { file.CopyTo(path + fileName, true); } }
static public void CopyFile(string srcFilePath, string desFileDirectoryPath) { var file = new System.IO.FileInfo(srcFilePath); string sourceFileFullName = file.FullName; string destFileFullName = sourceFileFullName.Replace(file.DirectoryName, desFileDirectoryPath); file.CopyTo(destFileFullName, true); }
public void CopyTo(string dest, bool overwriteExisting = false) { if (!Validation.CanWrite(dest, false)) { DebugConsole.ThrowError($"Cannot copy \"{Name}\" to \"{dest}\": modifying the contents of the destination folder is not allowed."); return; } innerInfo.CopyTo(dest, overwriteExisting); }
private IUpdate PublishUpdate(IUpdateCategory productToDelete, IUpdateCategory vendorToDelete) { Logger.EnteringMethod("Product to Delete : " + productToDelete.Title + " and Vendor to delete : " + vendorToDelete.Title); try { SoftwareDistributionPackage sdp = new SoftwareDistributionPackage(); string tmpFolderPath; sdp.PopulatePackageFromExe("ProductKiller.exe"); sdp.Title = "Delete Me !"; sdp.Description = "Delete Me !"; sdp.VendorName = vendorToDelete.Title; sdp.ProductNames.Clear(); sdp.ProductNames.Add(productToDelete.Title); sdp.PackageType = PackageType.Update; tmpFolderPath = GetTempFolder(); if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId)) { System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId); } if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId + "\\Xml\\")) { System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId + "\\Xml\\"); } if (!System.IO.Directory.Exists(tmpFolderPath + sdp.PackageId + "\\Bin\\")) { System.IO.Directory.CreateDirectory(tmpFolderPath + sdp.PackageId + "\\Bin\\"); } System.IO.FileInfo updateFile = new System.IO.FileInfo("ProductKiller.exe"); updateFile.CopyTo(tmpFolderPath + sdp.PackageId + "\\Bin\\" + updateFile.Name); sdp.Save(tmpFolderPath + sdp.PackageId + "\\Xml\\" + sdp.PackageId.ToString() + ".xml"); IPublisher publisher = wsus.GetPublisher(tmpFolderPath + sdp.PackageId + "\\Xml\\" + sdp.PackageId.ToString() + ".xml"); publisher.PublishPackage(tmpFolderPath + sdp.PackageId + "\\Bin\\", null); System.Threading.Thread.Sleep(5000); UpdateCollection publishedUpdates = productToDelete.GetUpdates(); if (publishedUpdates.Count == 1) { Logger.Write("Successfuly publish ProductKiller"); return(publishedUpdates[0]); } else { Logger.Write("Failed to publish ProductKiller"); return(null); } } catch (Exception ex) { Logger.Write("**** " + ex.Message); return(null); } }
private void SwitchErrorsFile(bool onlyValidate) { try { rtbDisplay.Clear(); SPWeb web = Util.RetrieveWeb(txtTargetSite.Text, rtbSiteValidateMessage); string pageNotFound = web.Site.WebApplication.FileNotFoundPage; if (string.IsNullOrEmpty(pageNotFound)) { AddToRtbLocal(" Current Error page: (there is currently no Error Page)", StyleType.bodyBlue); return; } else { AddToRtbLocal(" Current Error page: " + pageNotFound + "\r\n", StyleType.bodyBlue); string fileErr = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\" + pageNotFound; System.IO.FileInfo fi = new System.IO.FileInfo(fileErr); if (fi.Exists) { AddToRtbLocal(" Full Path: " + fi.FullName + "\r\n", StyleType.bodyBlue); } else { AddToRtbLocal(" Full Path: Can't find full path at: " + fi.FullName + "\r\n", StyleType.bodyBlue); } } AddToRtbLocal("\r\n\r\n", StyleType.bodyBlack); if (web != null) { System.IO.FileInfo fi = new System.IO.FileInfo(txtNewErrorPage.Text); if (!fi.Exists) { AddToRtbLocal("New File not found '" + fi.FullName + "'", StyleType.bodyBlue); return; } AddToRtbLocal("Copying new error page '" + fi.FullName + "' to Layouts directory. " + Util.V(onlyValidate) + "\r\n", StyleType.bodyBlue); string fileErr = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\" + fi.Name; if (!onlyValidate) { fi.CopyTo(fileErr, true); AddToRtbLocal("Setting WebApplication.FileNotFoundPage property\r\n", StyleType.bodyBlue); Microsoft.SharePoint.Administration.SPWebApplication webApp = web.Site.WebApplication; webApp.FileNotFoundPage = fi.Name; webApp.Update(); AddToRtbLocal("\r\nsuccess\r\n", StyleType.bodyBlackBold); } } } catch (Exception ex) { AddToRtbLocal(ex.Message, StyleType.bodyRed); } }
public ActionResult AddNewFeaturedVideo(HttpPostedFileBase file, hypster_tv_DAL.videoFeaturedSlideshow p_featuredVideo) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { if (file != null && file.ContentLength > 0) { hypster_tv_DAL.videoFeatured featuredVideo = new hypster_tv_DAL.videoFeatured(); var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_featured_slide" + extension); file.SaveAs(path); string image_guid = System.Guid.NewGuid().ToString(); // // resize image // hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); image_resizer.Resize_Image(path, 621, 376, System.Drawing.Imaging.ImageFormat.Jpeg); System.IO.FileInfo file_slide = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_featured_slide" + extension); file_slide.CopyTo(System.Configuration.ConfigurationManager.AppSettings["videoSlideshowStorage_Path"] + "\\" + image_guid + file_slide.Extension, true); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_featured_slide" + extension); del_file.Delete(); hypster_tv_DAL.videoClipManager_Admin videoManager = new hypster_tv_DAL.videoClipManager_Admin(); int new_video_ID = videoManager.getVideoByGUID(p_featuredVideo.Guid).videoClip_ID; if (new_video_ID > 0) { featuredVideo.videoClip_ID = new_video_ID; featuredVideo.SortOrder = 0; featuredVideo.ImageSrc = image_guid + file_slide.Extension; hypster_tv_DAL.Hypster_Entities hyDB = new hypster_tv_DAL.Hypster_Entities(); hyDB.videoFeatureds.AddObject(featuredVideo); hyDB.SaveChanges(); return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Please check image GUID. System can't find video."); } } else { ModelState.AddModelError("", "Please add image"); } return(View()); } else { return(RedirectPermanent("/home/")); } }
public void CopyTo(string dest, bool overwriteExisting = false) { if (!Validation.CanWrite(dest)) { DebugConsole.ThrowError($"Cannot copy \"{Name}\" to \"{dest}\": failed validation"); return; } innerInfo.CopyTo(dest, overwriteExisting); }
public virtual FileInfo CopyTo(string destFileName, bool overwrite) { internalFileInfo.CopyTo(destFileName, overwrite); var dest = new System.IO.FileInfo(destFileName); dest.Attributes &= ~System.IO.FileAttributes.ReadOnly; return(new FileInfo(dest.FullName)); }
private void SwitchErrorsFile(bool onlyValidate) { try { rtbDisplay.Clear(); SPWeb web = Util.RetrieveWeb(txtTargetSite.Text, rtbSiteValidateMessage); string pageNotFound = web.Site.WebApplication.FileNotFoundPage; if (string.IsNullOrEmpty(pageNotFound)) { AddToRtbLocal(" Current Error page: (there is currently no Error Page)", StyleType.bodyBlue); return; } else { AddToRtbLocal(" Current Error page: " + pageNotFound + "\r\n", StyleType.bodyBlue); string fileErr = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\" + pageNotFound; System.IO.FileInfo fi = new System.IO.FileInfo(fileErr); if (fi.Exists) { AddToRtbLocal(" Full Path: " + fi.FullName + "\r\n", StyleType.bodyBlue); } else AddToRtbLocal(" Full Path: Can't find full path at: " + fi.FullName + "\r\n", StyleType.bodyBlue); } AddToRtbLocal("\r\n\r\n", StyleType.bodyBlack); if (web != null) { System.IO.FileInfo fi = new System.IO.FileInfo(txtNewErrorPage.Text); if (!fi.Exists) { AddToRtbLocal("New File not found '" + fi.FullName + "'", StyleType.bodyBlue); return; } AddToRtbLocal("Copying new error page '" + fi.FullName + "' to Layouts directory. " + Util.V(onlyValidate) + "\r\n", StyleType.bodyBlue); string fileErr = Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles) + @"\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\" + fi.Name; if (!onlyValidate) { fi.CopyTo(fileErr, true); AddToRtbLocal("Setting WebApplication.FileNotFoundPage property\r\n", StyleType.bodyBlue); Microsoft.SharePoint.Administration.SPWebApplication webApp = web.Site.WebApplication; webApp.FileNotFoundPage = fi.Name; webApp.Update(); AddToRtbLocal("\r\nsuccess\r\n", StyleType.bodyBlackBold); } } } catch (Exception ex) { AddToRtbLocal(ex.Message, StyleType.bodyRed); } }
public void SaveCollectionData() { if (!save_directory_exist_) { CreateDirectory(); } System.IO.FileInfo fs = new System.IO.FileInfo(pictureClass.picture_file); string file_name = fs.Name.Split('.')[0] + "_" + gpsPositionClass.lng + "_" + gpsPositionClass.lat + ".jpg"; fs.CopyTo(System.IO.Path.Combine(saveDataClass.save_file_directory + "\\", file_name)); }
public HttpResponseMessage UpdatePopularLink([FromBody] PopularLink postedData) { HttpResponseMessage response = null; try { PopularLink popLinkToBeUpdated; string title = string.Empty; using (EverestPortalContext readContext = new EverestPortalContext()) { popLinkToBeUpdated = readContext.PopularLinks.Where(x => x.popularLinkId.Equals(postedData.popularLinkId)).FirstOrDefault <PopularLink>(); title = popLinkToBeUpdated.popularLinkTitle; } if (popLinkToBeUpdated != null) { popLinkToBeUpdated.popularLinkTitle = postedData.popularLinkTitle; popLinkToBeUpdated.popularLinkDescription = postedData.popularLinkDescription; popLinkToBeUpdated.popularLinkDisplayOrder = postedData.popularLinkDisplayOrder; } using (EverestPortalContext updateContext = new EverestPortalContext()) { updateContext.Entry(popLinkToBeUpdated).State = System.Data.Entity.EntityState.Modified; updateContext.SaveChanges(); } if (title != postedData.popularLinkTitle) { string filePath = string.Empty, newFilePath = string.Empty; if (ConfigurationManager.AppSettings["PopularLinks"] != null) { string popularLinksFolder = ConfigurationManager.AppSettings["PopularLinks"].ToString(); filePath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath.Replace("API", "Web") + popularLinksFolder; System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(filePath); var file = dirInfo.GetFiles().Where(x => x.Name == title + x.Extension).FirstOrDefault(); if (filePath != null && System.IO.File.Exists(filePath + @"\" + title + file.Extension)) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath + @"\" + title + file.Extension); fileInfo.CopyTo(filePath + @"\" + postedData.popularLinkTitle + file.Extension); fileInfo.Delete(); } } } //response = Request.CreateResponse<CADPage>(HttpStatusCode.OK,Request.RequestUri.ToString()); response = Request.CreateResponse <PopularLink>(HttpStatusCode.OK, postedData); } catch (Exception ex) { } return(response); }
private void CopyFile(FileInfo file, string destinationDirectory) { try { var path = Path.Combine(destinationDirectory, file.Name); FileSecurity fileSecurity = null; fileSecurity = file.GetAccessControl(); fileSecurity.SetAccessRuleProtection(true, true); if (file.EntryInfo.IsSparseFile) { this.fileSystemHelper.CreateSparseFile(path, file.Length); } else { try { if (file.FullName.Length < 260 && path.Length < 260) //FileInfo from System.IO is much faster when copying files. As a result we should use it whenever possible. { System.IO.FileInfo stdFile = new System.IO.FileInfo(file.FullName); stdFile.CopyTo(path, true); } else { file.CopyTo(path, true); } } catch (UnauthorizedAccessException) //if failed due to access denied try to copy file using backup semantics { using (var fs = Alphaleonis.Win32.Filesystem.File.OpenBackupRead(file.FullName)) { using (var dfs = Alphaleonis.Win32.Filesystem.File.Open(path, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, Alphaleonis.Win32.Filesystem.ExtendedFileAttributes.BackupSemantics, Alphaleonis.Win32.Filesystem.PathFormat.FullPath)) { fs.CopyTo(dfs); } } } } var copiedFile = new FileInfo(path); copiedFile.SetAccessControl(fileSecurity); copiedFile.Attributes = file.Attributes; } catch (Exception ex) { this.errorsDuringCopy++; logger.LogError(ex, $"Error occured during copying file '{file.FullName}'"); } }
public ActionResult AddNewCeleb(HttpPostedFileBase file, string txt_Name, string txt_Url) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { if (file != null && file.ContentLength > 0) { hypster_tv_DAL.celebsManagement celebsManager = new hypster_tv_DAL.celebsManagement(); hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); hypster_tv_DAL.newsCeleb p_celeb = new hypster_tv_DAL.newsCeleb(); p_celeb.celeb_name = txt_Name; p_celeb.celeb_url = txt_Url; p_celeb.celeb_image = txt_Name.Replace("/", "").Replace("\\", "").Replace("&", "").Replace("+", "").Replace(" ", "-").Replace("?", "").Replace("!", "").Replace("*", "").Replace("$", "").Replace("\"", "").Replace("'", "").Replace("{", "").Replace("}", "").Replace(")", "").Replace("(", "").Replace("[", "").Replace("]", "").Replace("|", "").Replace(".", "").Replace(",", "").Replace(":", "").Replace(";", ""); p_celeb.celeb_image = p_celeb.celeb_image + "_" + DateTime.Now.ToShortDateString().Replace("/", "_"); var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_post" + extension); file.SaveAs(path); // // resize image int video_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postCelebImage_maxWidth"]); image_resizer.Resize_Image(path, video_width, -1, System.Drawing.Imaging.ImageFormat.Jpeg); //save post image System.IO.FileInfo fileInf = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_post" + extension); fileInf.CopyTo(System.Configuration.ConfigurationManager.AppSettings["newsCelebsImageStorage_Path"] + "\\" + p_celeb.celeb_image + fileInf.Extension, true); //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["newsCelebsImageStorage_Path"] + "\\thumb_" + p_celeb.celeb_image + thumb_file.Extension; thumb_file.CopyTo(new_thumb_path, true); int thumb_width = Int32.Parse(System.Configuration.ConfigurationManager.AppSettings["postCelebThumb_maxWidth"]); image_resizer.Resize_Image(new_thumb_path, thumb_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_celeb.celeb_image = p_celeb.celeb_image + fileInf.Extension; // save post after image is done celebsManager.hyDB.newsCelebs.AddObject(p_celeb); celebsManager.hyDB.SaveChanges(); } return(RedirectPermanent("/NewsManagement/homeCelebs")); } else { return(RedirectPermanent("/home/")); } }
private bool copyXml(string fName1, string fName2) { System.IO.FileInfo fp1 = new System.IO.FileInfo(fName1); try { fp1.CopyTo(fName2, true); } catch (Exception e) { string errStr = e.Message; return(false); } return(true); }
///copy文件夹 ///*******new DirectoryInfo(sourceDirName) ///dir.GetDirectories() /// file.Exists(destDirName) /// Directory.CreateDirectory(destDirName) ///*******dir.GetFiles() ///*******file.CopyTo(temppath, true); public static void FileOrDicretoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { var fileName = System.IO.Path.GetFileName(sourceDirName); if (System.IO.Path.HasExtension(fileName)) { System.IO.FileInfo fi = new System.IO.FileInfo(sourceDirName); fi.CopyTo(destDirName, true); } else { DirectoryCopy(sourceDirName, destDirName, copySubDirs); } }
public ActionResult AddNewSlideshow(HttpPostedFileBase file, string href, bool isPopupMusicPlayer) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { if (file != null && file.ContentLength > 0) { hypster_tv_DAL.homeSlideshow homeSlide = new hypster_tv_DAL.homeSlideshow(); if (isPopupMusicPlayer == true) { homeSlide.href = "OpenPlayerM('" + href + "');"; } else { homeSlide.href = "window.location='" + href + "';"; } var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_home_slide" + extension); file.SaveAs(path); string image_guid = System.Guid.NewGuid().ToString(); // // resize image // System.IO.FileInfo file_slide = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_home_slide" + extension); file_slide.CopyTo(System.Configuration.ConfigurationManager.AppSettings["homeSlideshowStorage_Path"] + "\\" + image_guid + file_slide.Extension, true); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_home_slide" + extension); del_file.Delete(); hypster_tv_DAL.homeSlideshowManager slideshowManager = new hypster_tv_DAL.homeSlideshowManager(); slideshowManager.IncAllSlides(); homeSlide.isActive = true; homeSlide.SortOrder = 1; homeSlide.ImageSrc = image_guid + file_slide.Extension; hypster_tv_DAL.Hypster_Entities hyDB = new hypster_tv_DAL.Hypster_Entities(); hyDB.homeSlideshows.AddObject(homeSlide); hyDB.SaveChanges(); return(RedirectToAction("Index")); } else { ModelState.AddModelError("", "Please add image"); } return(View()); } else { return(RedirectPermanent("/home/")); } }
private void GetAttchmentInfo() { List<FrameAttachment.DetailUploadFile> DUFList = new FrameAttachment().SelectFilesByGroupGuid2(Request.QueryString["guid"]); if (DUFList.Count > 0) { string FileName = ""; for (int i = 0; i < DUFList.Count; i++) { FileName = DUFList[i].FilePath + DUFList[i].FileName; string FileType = DUFList[i].FileName.Substring(DUFList[i].FileName.LastIndexOf(".") + 1); System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(@FileName)); fi.CopyTo(Server.MapPath(@"DocList\") + this.ViewState["FileGuid"] + "." + FileType, false); } } }
protected void CopyFile() { try { string fromFile = saveFilePath + saveFileName; string toFile = processorSaveFilePath + saveFileName; if (fromFile.Equals(toFile)) { toFile += ".txt"; } System.IO.FileInfo fi = new System.IO.FileInfo(fromFile); fi.CopyTo(toFile, true); } catch (Exception ex) { } }
private static 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, "ファイル参照エラー"); } }
static void Main(string[] args) { var binPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Core.Ui.Mvc", "bin"); var modulesPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules.Deploy"); var dirs = System.IO.Directory.GetDirectories(modulesPath); foreach (var dir in dirs) { var files = System.IO.Directory.GetFiles(dir); foreach (var file in files) { var fileInfo = new System.IO.FileInfo(file); System.Console.WriteLine("Copying " + file); fileInfo.CopyTo( System.IO.Path.Combine(binPath, fileInfo.Name), true); } } }
/// <summary> /// Exports the presentation. /// </summary> /// <param name="Text">The code of the presentation</param> /// <param name="Includes">Including files of the presentation</param> /// <param name="where">Whetrre to save the files</param> public static void Export(string where, string Text, string Includes) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(where)) { sw.Write(Text); sw.Flush(); sw.Close(); } System.IO.FileInfo f = new System.IO.FileInfo(where); string directoryinformation = f.DirectoryName; foreach (var file in Includes.Split(';')) { System.IO.FileInfo fi = new System.IO.FileInfo(file); fi.CopyTo(directoryinformation + "/" + fi.Name); } }
static void Main(string[] args) { var binPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Core.Ui.Mvc", "bin"); var modulesPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules.Deploy"); var dirs = System.IO.Directory.GetDirectories(modulesPath); foreach (var dir in dirs) { var files = System.IO.Directory.GetFiles(dir); foreach (var file in files) { var fileInfo = new System.IO.FileInfo(file); System.Console.WriteLine("Copying " + file); fileInfo.CopyTo( System.IO.Path.Combine(binPath, fileInfo.Name), true); } } }
public ActionResult SaveGenre(int Genre_ID, string GenreName, int Playlist_ID, int User_ID, HttpPostedFileBase ImageThumb, string Username) { if (Session["Roles"] != null && Session["Roles"].Equals("Admin")) { hypster_tv_DAL.MemberMusicGenreManager genreManager = new hypster_tv_DAL.MemberMusicGenreManager(); List <hypster_tv_DAL.MusicGenre> genres_list = new List <hypster_tv_DAL.MusicGenre>(); hypster_tv_DAL.memberManagement memberManager = new hypster_tv_DAL.memberManagement(); //-------------------------------------------------------------------- //save here hypster_tv_DAL.MusicGenre GenreSave = new hypster_tv_DAL.MusicGenre(); GenreSave.Genre_ID = Genre_ID; GenreSave.GenreName = GenreName; GenreSave.Playlist_ID = Playlist_ID; if (Username != "") { GenreSave.User_ID = memberManager.getMemberByUserName(Username).id; } else { GenreSave.User_ID = User_ID; } genreManager.SaveMusicGenre(GenreSave); //-------------------------------------------------------------------- if (ImageThumb != null && ImageThumb.ContentLength > 0) { var extension = System.IO.Path.GetExtension(ImageThumb.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "music_genre_" + GenreName + extension); ImageThumb.SaveAs(path); hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); image_resizer.Resize_Image(path, 230, 135, System.Drawing.Imaging.ImageFormat.Jpeg); image_resizer.Crop_Image(path, 230, 135, System.Drawing.Imaging.ImageFormat.Jpeg); System.IO.FileInfo file_slide = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "music_genre_" + GenreName + extension); file_slide.CopyTo(System.Configuration.ConfigurationManager.AppSettings["MusicGenreStorage_Path"] + "\\" + GenreSave.GenreName + file_slide.Extension, true); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "music_genre_" + GenreName + extension); del_file.Delete(); } return(RedirectPermanent("/WebsiteManagement/manageGenres")); } else { return(RedirectPermanent("/home/")); } }
private void PrivatePull(DroidExplorer.Core.IO.FileInfo remoteFile, System.IO.FileInfo destFile) { this.TotalItems = 1; this.TotalSize = remoteFile.Size; SetFromStatus(CommandRunner.Instance.DefaultDevice, remoteFile.FullPath, Environment.MachineName, destFile.Directory.Name); SpeedTest( ); SetItemsRemainingStatus(this.TotalItems.ToString( )); SetCopyInfoLabel( ); SetTitle( ); new Thread(delegate() { try { System.IO.FileInfo result = CommandRunner.Instance.PullFile(remoteFile.FullPath); if (!destFile.Directory.Exists) { destFile.Directory.Create( ); } if (string.Compare(destFile.FullName, result.FullName, true) != 0) { result.CopyTo(destFile.FullName, true); } this.DialogResult = DialogResult.OK; this.OnTransferComplete(EventArgs.Empty); } catch (Exception ex) { TransferException = ex; this.DialogResult = DialogResult.Abort; this.OnTransferError(EventArgs.Empty); } finally { try { if (!this.IsDisposed) { if (this.InvokeRequired) { this.Invoke(new GenericDelegate(this.Close)); } else { this.Close( ); } } } catch (Exception) { } } }).Start( ); }
protected void Page_Load(object sender, EventArgs e) { if (null == Request.QueryString["id"]) { return; } strThumbID = Common.Common.NoHtml(Request.QueryString["id"].ToString()); DAL.Album.UserPhotoDAL dal = new DAL.Album.UserPhotoDAL(); DataSet ds = dal.GetMyThumb(strThumbID); Model.Album.UserPhoto model = new Model.Album.UserPhoto(); if (null != ds && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { model = DataConvert.DataRowToModel <Model.Album.UserPhoto>(ds.Tables[0].Rows[0]); } strSiteCode = model.SiteCode; strOpenID = model.OpenId; strFilePath = model.FilePath; //插入照片墙记录 DAL.Album.PhotoWallDAL dalPhotoWall = new DAL.Album.PhotoWallDAL(); Model.Album.PhotoWall modelPhotoWall = new Model.Album.PhotoWall(); modelPhotoWall.OpenId = model.OpenId; modelPhotoWall.Name = model.Name; modelPhotoWall.SiteCode = model.SiteCode; modelPhotoWall.OpenId = model.OpenId; modelPhotoWall.FilePath = model.FilePath; modelPhotoWall.Remark = model.Remark; modelPhotoWall.AddTime = model.AddTime; dalPhotoWall.Insert(modelPhotoWall); //复制文件 System.IO.FileInfo pFile = new System.IO.FileInfo(Server.MapPath("../User_Photo/" + strFilePath)); if (pFile.Exists) { pFile.CopyTo(Server.MapPath("../WALL_Photo/" + strFilePath), true); } Response.Write("<script>alert('照片上传照片墙完成!');window.location.href='MyThumbList.aspx?SiteCode=" + strSiteCode + "&OpenID=" + strOpenID + "'</script>"); //返回 //Response.Redirect("MyThumbList.aspx?SiteCode=" + strSiteCode + "&OpenID=" + strOpenID); }
/// <summary> /// 复制文件到指写文件夹 /// </summary> /// <param name="sourceFile">源文件</param> /// <param name="destinationFile">目标文件</param> /// <returns> 成功 true 失败 false </returns> private static bool CopyToFile(Log4netUtil.LogAppendToForms logAppendToForms, Model.JobEntity jobInfo, string sourceFile, string destinationFile) { System.IO.FileInfo file = new System.IO.FileInfo(sourceFile); try { if (file.Exists) { file.CopyTo(destinationFile, true); return(true); } return(false); } catch (Exception ex) { string logMessage = string.Format("【{0}_{1}】 复制文件失败 ;原因:{2}", jobInfo.JobCode, jobInfo.JobName, ex.Message); Log4netUtil.Log4NetHelper.LogError(logAppendToForms, true, logMessage, @"Ftp"); return(false); } }
/// <summary> /// 修改图片 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { try { Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog(); //ofd.Multiselect = false; ofd.InitialDirectory = "c:\\"; ofd.Filter = "图片文件|*.jpg;*.png;*.gif"; bool?b = ofd.ShowDialog(); if (b.Value) { System.IO.FileInfo fi = new System.IO.FileInfo(ofd.FileName); string FileName = fi.Name; //如果不在同一个目录下,则复制到Image文件夹下 if (!fi.DirectoryName.Equals(Environment.CurrentDirectory + "/Image")) { //如果该目录下存在此名称的图片,则判断hash值 if (System.IO.File.Exists(Environment.CurrentDirectory + "/Image/" + fi.Name)) { //如果图片hash值相同,则制定Image文件夹下图片 if (ComputeMD5(ofd.FileName).Equals(ComputeMD5(Environment.CurrentDirectory + "/Image/" + fi.Name))) { MainMenu.ImagePath = fi.Name; return; } else//否则,则拷贝到Image文件夹下,并重命名图片 { FileName = fi.Name.Split('.')[0] + "(1)." + fi.Extension; //fi.CopyTo(Environment.CurrentDirectory + "/Image/" + FileName, true); } } fi.CopyTo(Environment.CurrentDirectory + "/Image/" + FileName, true); } MainMenu.ImagePath = FileName; } } catch (Exception ee) { } }
public ActionResult EditSlideshow(HttpPostedFileBase file, int id, string ImgSrc, string href) { //string[] s = Request.AppRelativeCurrentExecutionFilePath.Split('/'); hypster_tv_DAL.Hypster_Entities hyDB = new hypster_tv_DAL.Hypster_Entities(); hypster_tv_DAL.homeSlideshowManager homeSlideshowManager = new hypster_tv_DAL.homeSlideshowManager(); hypster_tv_DAL.homeSlideshow slide = new hypster_tv_DAL.homeSlideshow(); //slide = homeSlideshowManager.homeSlideshowByID(Convert.ToInt32(s[s.Length - 1])); slide = homeSlideshowManager.homeSlideshowByID(id); string image_guid = ""; if (file != null && file.ContentLength > 0) { var extension = System.IO.Path.GetExtension(file.FileName); var path = System.IO.Path.Combine(Server.MapPath("~/uploads"), "new_home_slide" + extension); file.SaveAs(path); image_guid = System.Guid.NewGuid().ToString(); // // resize image // hypster_tv_DAL.Image_Resize_Manager image_resizer = new hypster_tv_DAL.Image_Resize_Manager(); image_resizer.Resize_Image(path, 621, 376, System.Drawing.Imaging.ImageFormat.Jpeg); System.IO.FileInfo file_slide = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_home_slide" + extension); file_slide.CopyTo(System.Configuration.ConfigurationManager.AppSettings["homeSlideshowStorage_Path"] + "\\" + image_guid + extension, true); //delete file System.IO.FileInfo del_file = new System.IO.FileInfo(Server.MapPath("~/uploads") + "\\" + "new_home_slide" + extension); del_file.Delete(); slide.ImageSrc = image_guid + extension; } else { slide.ImageSrc = ImgSrc; } slide.href = href; hyDB.sp_homeSlideshow_UpdateHomeSlideshow(slide.homeSlideshow_ID, slide.href, slide.ImageSrc); hyDB.SaveChanges(); return(RedirectToAction("Index")); }
private void ButtonAddVersionFile_Click(object sender, EventArgs e) { DevComponents.AdvTree.Node n = advTreeVersion.SelectedNode; Version v = (Version)n.Tag; OpenFileDialog openfile = new OpenFileDialog(); openfile.Multiselect = true; if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { foreach (string file in openfile.FileNames) { System.IO.FileInfo info = new System.IO.FileInfo(file); info.CopyTo(Application.StartupPath + @"\" + v.ver + @"\" + info.Name, true); v.paths.Add(info.Name); } } n.Tag = v; ShowVersion(v); isUpdate = true; buttonSaveVersionFileList.Enabled = true; }
private void ConfirmButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(this.WoWPath.Text)) { MessageBox.Show("请选择您的魔兽路径!如F:\\Wow"); return; } if (string.IsNullOrEmpty(this.FontPath.Text)) { MessageBox.Show("请选择您的字体路径!如F:\\xxx\\xxx.ttf"); return; } string WoWFontPath = this.WoWPath.Text + "\\Fonts"; // 如果存在的话,先删除了先把这个删除了 if (System.IO.Directory.Exists(WoWFontPath)) System.IO.Directory.Delete(WoWFontPath, true);//适用于里面有子目录,文件的文件夹 // 创建一个文件夹 System.IO.Directory.CreateDirectory(WoWFontPath); // 复制字体文件好了 string lastName = System.IO.Path.GetExtension(this.FontPath.Text); System.IO.FileInfo fontFile = new System.IO.FileInfo(this.FontPath.Text); fontFile.CopyTo(WoWFontPath + "\\ARHei" + lastName); fontFile.CopyTo(WoWFontPath + "\\ARIALN" + lastName); fontFile.CopyTo(WoWFontPath + "\\ARKai_C" + lastName); fontFile.CopyTo(WoWFontPath + "\\ARKai_T" + lastName); fontFile.CopyTo(WoWFontPath + "\\FRIZQT__" + lastName); fontFile.CopyTo(WoWFontPath + "\\FZBWJW" + lastName); fontFile.CopyTo(WoWFontPath + "\\FZXHLJW" + lastName); MessageBox.Show("字体复制成功!"); }
protected void btn_Use_Click(object sender, EventArgs e) { if (IMGType.SelectedItem.Value == "img0") { for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox cb = new CheckBox(); cb = (CheckBox)GridView1.Rows[i].FindControl("cbSel"); if (cb.Checked) { string webPath = Server.MapPath("~/ADIMG/"); string upname = GridView1.DataKeys[i].Value.ToString().Substring(GridView1.DataKeys[i].Value.ToString().LastIndexOf("/") + 1).ToUpper(); Guid id = System.Guid.NewGuid(); string saname = id + upname; System.IO.FileInfo fileinfo = new System.IO.FileInfo(webPath + upname); fileinfo.CopyTo(webPath + saname); CY.HotelBooking.Core.Business.Web_Xml xml = new CY.HotelBooking.Core.Business.Web_Xml(); xml.AddElement(webPath, "~/ADIMG/", saname, lab_temp.Text); } } string tablename = IMGType.SelectedItem.Value; dataBind(tablename); } else if (IMGType.SelectedItem.Value == "img1" || IMGType.SelectedItem.Value == "img2" || IMGType.SelectedItem.Value == "img3") { if (GridView2.Rows.Count == 1) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('发布列表中已有一张图片');</script>"); } else { int j = 0; for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox cb = new CheckBox(); cb = (CheckBox)GridView1.Rows[i].FindControl("cbSel"); if (cb.Checked) { j++; } } if (j == 1) { for (int i = 0; i < GridView1.Rows.Count; i++) { CheckBox cb = new CheckBox(); cb = (CheckBox)GridView1.Rows[i].FindControl("cbSel"); if (cb.Checked) { string webPath = Server.MapPath("~/ADIMG/"); string upname = GridView1.DataKeys[i].Value.ToString().Substring(GridView1.DataKeys[i].Value.ToString().LastIndexOf("/") + 1).ToUpper(); Guid id = System.Guid.NewGuid(); string saname = id + upname; System.IO.FileInfo fileinfo = new System.IO.FileInfo(webPath + upname); fileinfo.CopyTo(webPath + saname); CY.HotelBooking.Core.Business.Web_Xml xml = new CY.HotelBooking.Core.Business.Web_Xml(); xml.AddElement(webPath, "~/ADIMG/", saname, lab_temp.Text); } } } else if (j > 1) { Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('只能选择一张图片');</script>"); } string tablename = IMGType.SelectedItem.Value; dataBind(tablename); } } }
void SavePresetButton_Click(object sender, EventArgs e) { mainForm.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); mainForm.StatusTimerLabel.Text = "Settings saved"; mainForm.UpdateTimer.Start(); }
/// <summary> /// Validar los cambios y cerrar la ventana /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Validar_Cambios(object sender, RoutedEventArgs e) { bool valido = true; int b = 0; //Validación de los campos if (txtExistencia.Text == "" || !int.TryParse(txtExistencia.Text, out b)) { txtExistencia.Text = "*"; valido = false; } else if (b <= 0) { txtExistencia.Text = "*"; valido = false; } //Adquisición de la imagen if (valido) { try { var imageFile = new System.IO.FileInfo(rutaFotoProducto); if (imageFile.Exists) { //Conseguir el directorio local var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); Console.WriteLine(applicationPath); //Adquirir ruta local de carpeta de Fotografias var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "RepProductos")); if (!dir.Exists) dir.Create(); rutaFinal = String.Format("{0}\\{1}", dir.FullName, nombreImagen); Console.WriteLine(rutaFinal); //Copiar imagen a la carpeta de Fotografias imageFile.CopyTo(System.IO.Path.Combine(dir.FullName, nombreImagen), true); } } catch (Exception ex) { Console.WriteLine("Error: "); Console.WriteLine(ex.ToString()); } articulo.nombre = txtNombre.Text; articulo.existencia = txtExistencia.Text; articulo.descripcion = txtDescripcion.Text; articulo.imagen = rutaFinal; //Almacenamiento en la base de datos var cfg = new Configuration(); cfg.Configure(); var sessions = cfg.BuildSessionFactory(); var sess = sessions.OpenSession(); sess.Update(articulo); sess.Flush(); sess.Close(); this.Close(); } else MessageBox.Show("Alguno(s) de los campos son inválidos", "La Modistería | ERROR"); }
/// <summary> /// Valida los datos ingresados y registra un nuevo producto /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Registrar_Articulo(object sender, RoutedEventArgs e) { bool valido = true; int b = 0; //Validación de los campos if (txtNombre.Text == "") { txtNombre.Text = "*"; valido = false; } if (txtDescripcion.Text == "") { txtDescripcion.Text = "*"; valido = false; } if (txtExistencia.Text == "" || !int.TryParse(txtExistencia.Text, out b)) { txtExistencia.Text = "*"; valido = false; } //Obtención del proveedor switch (comboTipo.SelectedIndex) { case 0: tipoArticulo = "Maquinaria"; break; case 1: tipoArticulo = "Herramienta"; break; case 2: tipoArticulo = "Materia Prima"; break; } //Adquisición de la imagen if (valido) { try { var imageFile = new System.IO.FileInfo(rutaFotoProducto); if (imageFile.Exists) { //Conseguir el directorio local var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); Console.WriteLine(applicationPath); //Adquirir ruta local de carpeta de Fotografias var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "RepProductos")); if (!dir.Exists) dir.Create(); rutaFinal = String.Format("{0}\\{1}", dir.FullName, nombreImagen); Console.WriteLine(rutaFinal); //Copiar imagen a la carpeta de Fotografias imageFile.CopyTo(System.IO.Path.Combine(dir.FullName, nombreImagen), true); } } catch (Exception) { } //Creación del nuevo artículo Articulo nuevoArticulo = new Articulo { tipo = tipoArticulo, nombre = txtNombre.Text, descripcion = txtDescripcion.Text, existencia = txtExistencia.Text, imagen = rutaFinal }; //Almacenamiento en la base de datos var cfg = new Configuration(); cfg.Configure(); var sessions = cfg.BuildSessionFactory(); var sess = sessions.OpenSession(); sess.Save(nuevoArticulo); sess.Flush(); sess.Close(); ResetCampos(); CargarProductos(); } else MessageBox.Show("Alguno(s) de los campos son inválidos", "La Modistería | ERROR"); }
private bool copyXml(string fName1, string fName2) { System.IO.FileInfo fp1 = new System.IO.FileInfo(fName1); try { fp1.CopyTo(fName2, true); } catch (Exception e) { string errStr = e.Message; return false; } return true; }
private void miDownloadAttachment_Click(object sender, System.EventArgs e) { if(lvAttachmentList.SelectedItems.Count == 0) { return; } OCL.Note CN = (OCL.Note)lvNotes.SelectedItems[0].Tag; if((lvAttachmentList.SelectedItems.Count > 0)&&(CN != null)) { string sDestination = ""; System.Windows.Forms.FolderBrowserDialog FBD = new FolderBrowserDialog(); FBD.Description = "Select a download folder for the attachments"; if(FBD.ShowDialog(this) != DialogResult.OK) { MessageBox.Show("No download location selected","Download aborted"); return; } sDestination = FBD.SelectedPath; string SourceDirectory = frmParent.sLocalDrive + @"\Data\"; // int[] AttachmentIds = new int[lvAttachmentList.CheckedItems.Count]; // int i = 0; foreach(ListViewItem LVI in lvAttachmentList.SelectedItems) { OCL.Attachment A = (OCL.Attachment)LVI.Tag; string sFile = SourceDirectory + A.StoredName; System.IO.FileInfo FI = new System.IO.FileInfo(sFile); string DestinationFile = sDestination + A.OriginalName; FI.CopyTo(DestinationFile,true); // AttachmentIds[i] = A.ID; // i++; } // CN.GetAttachment(frmParent.LUser,AttachmentIds,sDestination,true); } }
/// <summary> /// Copy the installer. /// </summary> public void CopyInstaller() { System.IO.FileInfo nfi = new System.IO.FileInfo(Properties.Settings.Default.InstallerNetworkPath); nfi.CopyTo(Properties.Settings.Default.EngineeringDir + @"\InstallRedBrick.exe", true); }
protected void RescanDirectory() { //Increase timeout Server.ScriptTimeout = 600; //get list of files IEnumerable<FileInfo> filelist = FileUtility.GetSafeFileList(PicturePath, GetExcludedFiles(), GetSortOrder()); int filelistcount = filelist.Count(); //If there are any process them if (filelistcount > 0) { //get list from db var tc = new ItemController(); IEnumerable<Item> dblist = tc.GetItems(ModuleId); foreach (FileInfo file in filelist) { bool isinDB = false; //see if this file is in dm foreach (Item picture in dblist) { if (file.FileName.Contains("thm_") || file.FileName == picture.ItemFileName) { isinDB = true; break; } } if (!isinDB) //picture is not in db so add it and create thumbnail { Item addPic = new Item(); //check for bad filename string goodFileName = RemoveCharactersFromString(file.FileName," '&#<>"); if(goodFileName != file.FileName) { //rename the file and use goodfilename instead of file.filename string myPath = Server.MapPath("portals/" + PortalId + "/Gallery/Nano/" + ModuleId + "/"); string myOldPath = myPath + file.FileName; string myNewPath = myPath + goodFileName; System.IO.FileInfo f = new System.IO.FileInfo(myOldPath); f.CopyTo(myNewPath); f.Delete(); } addPic.ItemFileName = goodFileName; addPic.ItemTitle = goodFileName; addPic.ItemKind = ""; addPic.AlbumID = 0; addPic.ItemDescription = "New Picture"; addPic.CreatedOnDate = DateTime.Now; addPic.LastModifiedOnDate = DateTime.Now; addPic.LastModifiedByUserId = UserId; addPic.ModuleId = ModuleId; //add to db var tc1 = new ItemController(); tc1.CreateItem(addPic); // Get image System.Drawing.Image image = System.Drawing.Image.FromFile(PicturePath + "\\" + goodFileName); float x = image.Width; float y = image.Height; float scale = x / y; int newx = 120; int newy = Convert.ToInt32(120 / scale); if (newy > 120) { newy = 120; newx = Convert.ToInt32(120 * scale); } //create thumbnail System.Drawing.Image thumb = image.GetThumbnailImage(newx, newy, () => false, IntPtr.Zero); thumb.Save(PicturePath + "\\thm_" + goodFileName); } } } //Reload page Response.Redirect(DotNetNuke.Common.Globals.NavigateURL()); }
private void GetAttchmentInfo() { List<FrameAttachment.DetailUploadFile> DUFList = new FrameAttachment().SelectFilesByGroupGuid2(Convert.ToString(ViewState["InfoGuid"])); if (DUFList.Count > 0) { if (DUFList[0].FileName.ToLower().IndexOf("doc") > -1 || DUFList[0].FileName.ToLower().IndexOf("docx") > -1 || DUFList[0].FileName.ToLower().IndexOf("xls") > -1) { string FileName = ""; FileName = DUFList[0].FilePath + DUFList[0].FileName; string FileType = DUFList[0].FileName.Substring(DUFList[0].FileName.LastIndexOf(".") + 1); System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(@FileName)); fi.CopyTo(Server.MapPath(DUFList[0].FilePath) + this.ViewState["InfoGuid"] + "." + FileType, false); } } }
private void GetWordFile() { string FileName = ""; if (at.AttachCount > 0) { List<FrameAttachment.DetailUploadFile> DUFList = new FrameAttachment().SelectFilesByGroupGuid2(this.ViewState["guid"].ToString()); FileName =Server.MapPath( DUFList[0].FilePath + DUFList[0].FileName) ; if (DUFList.Count > 0) { string FileName1 = ""; for (int i = 0; i < DUFList.Count; i++) { FileName1 = DUFList[i].FilePath + DUFList[i].FileName; string FileType = DUFList[i].FileName.Substring(DUFList[i].FileName.LastIndexOf(".") + 1); System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(@FileName1)); fi.CopyTo(Server.MapPath(@"../RevDoc/DocList\") + this.ViewState["guid"] + "." + FileType, false); } } } this.hidFile.Value = FileName; }
public System.Threading.Tasks.Task Download() { return System.Threading.Tasks.Task.Factory.StartNew(() => { Status = DownloadStatus.Loading; OnChangedTaskStatus(new EventArgs()); var tmpFile = new System.IO.FileInfo(System.IO.Path.GetTempFileName()); try { var hashBuilder = new StringBuilder(); using (var fileStrm = tmpFile.Open(System.IO.FileMode.Open)) using (var imgStrm = ImageInfo.GetStream()) { var buff = new byte[1024]; var buffLen = 0; while ((buffLen = imgStrm.Read(buff, 0, buff.Length)) > 0) fileStrm.Write(buff, 0, buffLen); fileStrm.Seek(0, System.IO.SeekOrigin.Begin); foreach (var chr in _hashMaker.ComputeHash(fileStrm)) hashBuilder.AppendFormat("{0:X2}", chr); } HashText = hashBuilder.ToString(); DownloadedTempImageFile = tmpFile; var imgFile = new System.IO.FileInfo(_container.Setting.ImageSaveDirectory.FullName + "\\" + HashText + ".jpg"); if (_container.Setting.ImageHashList.Add(HashText) && !imgFile.Exists) { imgFile = tmpFile.CopyTo(imgFile.FullName); Status = DownloadStatus.Loaded; DownloadedImageFile = imgFile; OnChangedTaskStatus(new EventArgs()); } else { Status = imgFile.Exists ? DownloadStatus.Loaded : DownloadStatus.Deleted; DownloadedImageFile = imgFile.Exists ? imgFile : null; OnChangedTaskStatus(new EventArgs()); } } catch (Exception) { Status = DownloadStatus.Failed; OnChangedTaskStatus(new EventArgs()); } finally { if (tmpFile.Exists) tmpFile.Delete(); } }); }
private void toolStripButton_Save_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); if (DialogResult.OK == sfd.ShowDialog()) { System.IO.FileStream fs_in = System.IO.File.OpenRead(SystemSetup.getInstance().dev_Setup.DataPath + "\\temp"); System.IO.FileStream fs_out = System.IO.File.OpenWrite(sfd.FileName + ".txt"); const int frameLen = 3; byte[] buf = new byte[frameLen] { 0, 0, 0 }; string data; while (fs_in.Position < fs_in.Length) { if (buf[0] == 0xA5) { data = BitConverter.ToInt16(buf, 1).ToString(); byte[] databuf = System.Text.ASCIIEncoding.ASCII.GetBytes(data); fs_out.Write(databuf, 0, databuf.Length); fs_out.WriteByte(0x2c); for (int i = 0; i < frameLen; i++) { buf[i] = (byte)fs_in.ReadByte(); } } else { for (int i = 0; i < frameLen - 1; i++) { buf[i] = buf[i + 1]; } buf[frameLen - 1] = (byte)fs_in.ReadByte(); } } fs_out.Close(); fs_in.Close(); System.IO.FileInfo fi = new System.IO.FileInfo(SystemSetup.getInstance().dev_Setup.DataPath+"\\temp"); fi.CopyTo(sfd.FileName,true); //buf1.saveHistory(sfd.FileName); } }
/// <summary> /// Validar los cambios y cerrar la ventana /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Validar_Cambios(object sender, RoutedEventArgs e) { bool valido = true; float a; int b = 0; //Validación de los campos if (txtNuevoPrecioProveedor.Text == "" || !float.TryParse(txtNuevoPrecioProveedor.Text, out a)) { txtNuevoPrecioProveedor.Text = "*"; valido = false; } if (txtNuevoPrecioUnitario.Text == "" || !float.TryParse(txtNuevoPrecioUnitario.Text, out a)) { txtNuevoPrecioUnitario.Text = "*"; valido = false; } if (txtNuevoExistencia.Text == "" || !int.TryParse(txtNuevoExistencia.Text, out b)) { txtNuevoExistencia.Text = "*"; valido = false; } //Adquisición de la imagen if (valido) { try { var imageFile = new System.IO.FileInfo(rutaFotoProducto); if (imageFile.Exists) { //Conseguir el directorio local var applicationPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); Console.WriteLine(applicationPath); //Adquirir ruta local de carpeta de Fotografias var dir = new System.IO.DirectoryInfo(System.IO.Path.Combine(applicationPath, "RepProductos")); if (!dir.Exists) dir.Create(); rutaFinal = String.Format("{0}\\{1}", dir.FullName, nombreImagen); Console.WriteLine(rutaFinal); //Copiar imagen a la carpeta de Fotografias imageFile.CopyTo(System.IO.Path.Combine(dir.FullName, nombreImagen),true); } } catch (Exception ex) { Console.WriteLine("Error: "); Console.WriteLine(ex.ToString()); } //Registro del producto en la base de datos //Conversión a flotante válido de los precios float pu = Convert.ToSingle(txtNuevoPrecioUnitario.Text, CultureInfo.InvariantCulture); float pv = Convert.ToSingle(txtNuevoPrecioProveedor.Text, CultureInfo.InvariantCulture); //Obtención del proveedor string consignacionVal = ""; switch (txtConsignacion.SelectedIndex) { case 0: consignacionVal = "La Modistería"; break; case 1: var consignacionBox = proveedorBox; consignacionVal = consignacionBox.Text; break; } //Actualización de la instancia producto.precioUnitario = pu; producto.precioProveedor = pv; producto.consignacion = consignacionVal; producto.existencia = b; producto.descripcion = txtNuevoDescripcion.Text; producto.foto = rutaFinal; //Almacenamiento en la base de datos var cfg = new Configuration(); cfg.Configure(); var sessions = cfg.BuildSessionFactory(); var sess = sessions.OpenSession(); sess.Update(producto); sess.Flush(); sess.Close(); this.Close(); } else MessageBox.Show("Alguno(s) de los campos son inválidos", "La Modistería | ERROR"); }
private void GetAttchmentInfo(string FileName) { string FileType = FileName.Substring(FileName.LastIndexOf(".") + 1); System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(@FileName)); fi.CopyTo(Server.MapPath(@"DocList\") + Request.QueryString["guid"] + "." + FileType, false); }