/// <summary> /// Remove the old, unnecessary files /// </summary> private void TempImgLRU() { int nLURInterval = 30; // LUR every ? seconds int nMaxFilesCount = 100; // Only LRU when files count exceed this threshold int nMaxExpiredMinutes = 30; // Only delete the files expired with specified minutes string strTempFolder = Yiyou.Util.ImageUtils.GetTempFolderPath(); while (System.IO.Directory.Exists(strTempFolder)) { try { string[] FileList = System.IO.Directory.GetFiles(strTempFolder, "*.*", System.IO.SearchOption.AllDirectories); if (FileList.Length > nMaxFilesCount) { foreach (string filePath in FileList) { System.IO.FileInfo fi = new System.IO.FileInfo(filePath); if (fi.LastAccessTime.AddMinutes(nMaxExpiredMinutes) < DateTime.Now) { fi.Attributes = System.IO.FileAttributes.Normal; fi.Delete(); } } } } catch (Exception ex) { Log4NetLogger.GetLogger().Info("LRU failed: " + ex.StackTrace); } System.Threading.Thread.Sleep(nLURInterval * 1000); } }
public async Task ShouldBeAbleToUploadTheSameFileTwice() { string testFileName = $"test-{Guid.NewGuid():D}.txt"; string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, testFileName); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); for (int i = 0; i < 2; ++i) { await driver.GoToUrl(formsPage); IWebElement uploadElement = await driver.FindElement(By.Id("upload")); Assert.That(await uploadElement.GetAttribute("value"), Is.Null.Or.EqualTo(string.Empty)); await uploadElement.SendKeys(inputFile.FullName); await uploadElement.Submit(); } inputFile.Delete(); // If we get this far, then we're all good. }
public void SingleCaptureJPGAndSendFTP(string ftphost, string username, string password) { try { ftp = new FtpClient(ftphost, username, password); nameOfFile = string.Format("{0}.{1}.{2} - {3}.{4}.{5}.jpg", DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2, '0'), DateTime.Now.Day.ToString().PadLeft(2, '0'), DateTime.Now.Hour.ToString().PadLeft(2, '0'), DateTime.Now.Minute.ToString().PadLeft(2, '0'), DateTime.Now.Second.ToString().PadLeft(2, '0')); //capture a JPG //System.Drawing.Image fileImage = (System.Drawing.Image)ScreenCapturing.GetDesktopWindowCaptureAsBitmap(); System.Drawing.Image fileImage = (System.Drawing.Image)CaptureScreen.GetDesktopImage(); fileImage.Save(this.nameOfFile, System.Drawing.Imaging.ImageFormat.Jpeg); //send a JPG to FTP Server ftp.Login(); this.CreateFolder(); ftp.Upload(nameOfFile); ftp.Close(); System.IO.FileInfo file = new System.IO.FileInfo(this.nameOfFile); file.Delete(); } catch {} finally { GC.Collect(); } }
internal override void DeleteDatabase() { if (!string.IsNullOrWhiteSpace(DBName)) { SqlHelper.Execute("USE master;"); SqlHelper.Execute($"ALTER DATABASE [{DBName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"); SqlHelper.Execute($"DROP DATABASE [{DBName}]"); DBName = null; } try { foreach (var t in TempFiles.ToList()) { var file = new System.IO.FileInfo(t); if (file.Exists) { file.Delete(); } TempFiles.Remove(t); } //TempFiles.Clear(); } catch (Exception ex) { WriteLine(ex.ToString()); } }
public void Teardown() { if (testFile != null && testFile.Exists) { testFile.Delete(); } }
// DELETE /api/music/5 public HttpResponseMessage Delete(Guid id) { HttpResponseMessage response = new HttpResponseMessage(); string filePath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3"; if (System.IO.File.Exists(filePath)) { System.IO.FileInfo fi = new System.IO.FileInfo(filePath); try { fi.Delete(); response.StatusCode = System.Net.HttpStatusCode.OK; //Hreinsum cacheið HttpContext.Current.Cache.Remove("songlist"); } catch (System.IO.IOException e) { response.StatusCode = System.Net.HttpStatusCode.Unauthorized; } } else { response.StatusCode = System.Net.HttpStatusCode.NotFound; } return response; }
public bool SaveAs(string filepath) { if (excel == null) { ErrorString = "模板文件格式错误"; return(false); } if (dataSheet != null) { return(true); } var fi = new System.IO.FileInfo(filepath); if (!fi.Directory.Exists) { fi.Directory.Create(); } if (fi.Exists) { fi.Delete(); } if (!excel.Save(fi.FullName)) { ErrorString = excel.ErrorString; } return(true); }
public static DataTable IfDataTableXMLExist(string FileName, decimal SurvivalTime) { DataTable dt = new DataTable(); decimal dateDiff = 0; string dtFileName = "D:\\ReprotServer\\CreateXML\\" + FileName + ".xml"; try { if (System.IO.File.Exists(dtFileName)) { System.IO.FileInfo file = new System.IO.FileInfo(dtFileName); TimeSpan ts = DateTime.Now - file.CreationTime; dateDiff = Convert.ToDecimal(ts.TotalMinutes.ToString()); if (dateDiff < SurvivalTime) { dt.ReadXml(dtFileName); } else { file.Delete(); dt = null; } } else { dt = null; } } catch (Exception ex) { throw ex; } return(dt); }
private void SaveFile() { // Delete any existing file with the same name System.IO.FileInfo fileInfo = new System.IO.FileInfo(iFileName); if (fileInfo.Exists) { fileInfo.Delete(); } // Save and tidy up try { iWorkbook.SaveAs(iFileName, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); } catch (System.IO.IOException) { } iWorkbook.Close(false, Type.Missing, Type.Missing); }
public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() { // IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to // download it if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = xhtmlFormPage; IWebElement uploadElement = driver.FindElement(By.Id("file")); Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value")); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); }
/* * 7 个静态函数 * 私有函数 * private bool FileDelete() : 删除文件 * private void FolderClear() : 清除文件夹内的所有文件 * private void RunCmd() : 运行内部命令 * * 公有函数 * public void CleanCookie() : 删除Cookie * public void CleanHistory() : 删除历史记录 * public void CleanTempFiles() : 删除临时文件 * public void CleanAll() : 删除所有 * * * * */ //private /// /// 删除一个文件,System.IO.File.Delete()函数不可以删除只读文件,这个函数可以强行把只读文件删除。 /// /// 文件路径 /// 是否被删除 static bool FileDelete(string path) { //first set the File\'s ReadOnly to 0 //if EXP, restore its Attributes System.IO.FileInfo file = new System.IO.FileInfo(path); System.IO.FileAttributes att = 0; bool attModified = false; try { //### ATT_GETnSET att = file.Attributes; file.Attributes &= (~System.IO.FileAttributes.ReadOnly); attModified = true; file.Delete(); } catch (Exception e) { if (attModified) { file.Attributes = att; } return(false); } return(true); }
// DELETE /api/music/5 public HttpResponseMessage Delete(Guid id) { HttpResponseMessage response = new HttpResponseMessage(); string filePath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3"; if (System.IO.File.Exists(filePath)) { System.IO.FileInfo fi = new System.IO.FileInfo(filePath); try { fi.Delete(); response.StatusCode = System.Net.HttpStatusCode.OK; //Hreinsum cacheið HttpContext.Current.Cache.Remove("songlist"); } catch (System.IO.IOException e) { response.StatusCode = System.Net.HttpStatusCode.Unauthorized; } } else { response.StatusCode = System.Net.HttpStatusCode.NotFound; } return(response); }
public void SingleCaptureJPGAndSendFTP(string ftphost,string username,string password) { try { ftp = new FtpClient(ftphost,username,password); nameOfFile = string.Format( "{0}.{1}.{2} - {3}.{4}.{5}.jpg", DateTime.Now.Year, DateTime.Now.Month.ToString().PadLeft(2,'0'), DateTime.Now.Day.ToString().PadLeft(2,'0'), DateTime.Now.Hour.ToString().PadLeft(2,'0'), DateTime.Now.Minute.ToString().PadLeft(2,'0'), DateTime.Now.Second.ToString().PadLeft(2,'0')); //capture a JPG //System.Drawing.Image fileImage = (System.Drawing.Image)ScreenCapturing.GetDesktopWindowCaptureAsBitmap(); System.Drawing.Image fileImage = (System.Drawing.Image)CaptureScreen.GetDesktopImage(); fileImage.Save( this.nameOfFile , System.Drawing.Imaging.ImageFormat.Jpeg ); //send a JPG to FTP Server ftp.Login(); this.CreateFolder(); ftp.Upload(nameOfFile); ftp.Close(); System.IO.FileInfo file = new System.IO.FileInfo(this.nameOfFile); file.Delete(); } catch {} finally { GC.Collect(); } }
public void fatalMessageAndException() { string path = "C:\\UIT"; System.IO.FileInfo fi = new System.IO.FileInfo(path + "\\log.txt"); string text = "Log function is OK. Exception is also OK"; DebugException ex = new DebugException("Someone divide 1 by 0"); string expectedValue = CurrentUser.Instance.FullName + ". " + DateTime.Now.ToString() + ". " + LogLevel.Fatal.ToString() + ": " + text + ". \r\n" + ex.ToString() + "\r\n"; FileLogger.getInstance(path, "log.txt", TextFormatter.Instance).fatal(text, ex); string actualValue = ""; using (System.IO.StreamReader file = new System.IO.StreamReader(path + "\\log.txt", true)) { while (!file.EndOfStream) { string line = file.ReadLine(); actualValue = line; while (line != "") { line = file.ReadLine(); actualValue += "\r\n" + line; } } file.Close(); } fi.Delete(); Assert.AreEqual(expectedValue, actualValue); }
public void fatalMessage() { string path = "C:\\UIT"; System.IO.FileInfo fi = new System.IO.FileInfo(path + "\\log.txt"); string text = "Log function is OK"; string expectedValue = CurrentUser.Instance.FullName + ". " + DateTime.Now.ToString() + ". " + LogLevel.Fatal.ToString() + ": " + text; FileLogger.getInstance(path, "log.txt", TextFormatter.Instance).fatal(text); string actualValue = ""; using (System.IO.StreamReader file = new System.IO.StreamReader(path + "\\log.txt", true)) { while (!file.EndOfStream) { actualValue = file.ReadLine(); file.ReadLine(); } file.Close(); } Assert.AreEqual(expectedValue, actualValue); fi.Delete(); }
static void DumpNPCs(int maxNPCs) { var list = new List <NPCInfo>(); for (var npcId = -65; npcId <= maxNPCs; npcId++) { var npc = Activator.CreateInstance(typeof(Terraria.NPC)) as Terraria.NPC; npc.netDefaults(npcId); if (npc.name == String.Empty) { continue; } if (npc.boss) { list.Add(new NPCInfo() { Name = npc.name.Trim(), NetId = npc.netID, Id = npc.type, Boss = true }); } else { list.Add(new NPCInfo() { Name = npc.name.Trim(), NetId = npc.netID, Id = npc.type }); } } var writable = list .Distinct() .OrderBy(x => x.Name) .ToArray(); //var bf = new BinaryFormatter(); var bf = new XmlSerializer(typeof(DefinitionFile <NPCInfo>)); var info = new System.IO.FileInfo("npc.xml"); if (info.Exists) { info.Delete(); } using (var fs = info.OpenWrite()) { bf.Serialize(fs, new DefinitionFile <NPCInfo>() { Version = 2, Data = writable }); fs.Flush(); } bf = null; }
public async Task UploadingFileShouldFireOnChangeEvent() { await driver.GoToUrl(formsPage); IWebElement uploadElement = await driver.FindElement(By.Id("upload")); IWebElement result = await driver.FindElement(By.Id("fileResults")); Assert.AreEqual(string.Empty, await result.Text()); string filePath = System.IO.Path.Combine(EnvironmentManager.Instance.CurrentDirectory, "test.txt"); System.IO.FileInfo inputFile = new System.IO.FileInfo(filePath); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); await uploadElement.SendKeys(inputFile.FullName); // Shift focus to something else because send key doesn't make the focus leave await driver.FindElement(By.Id("id-name1")).Click(); inputFile.Delete(); Assert.AreEqual("changed", await result.Text()); }
public void PostData(string accesstoken, string accesstokensecret, string Hostname, string body, string title, string type) { try { oAuthTumbler.TumblrConsumerKey = ConfigurationManager.AppSettings["TumblrClientKey"]; oAuthTumbler.TumblrConsumerSecret = ConfigurationManager.AppSettings["TumblrClientSec"]; var prms = new Dictionary <string, object>(); var postUrl = string.Empty; if (type == "text") { prms.Add("type", "text"); prms.Add("title", title); prms.Add("body", body); // var postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/posts/text?api_key=" + oAuthTumbler.TumblrConsumerKey; postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post"; } if (type == "quote") { prms.Add("type", "quote"); prms.Add("quote", title); prms.Add("source", body); postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post"; } else if (type == "photo") { // Load file meta data with FileInfo System.IO.FileInfo fileInfo = new System.IO.FileInfo(title); // The byte[] to save the data in byte[] data = new byte[fileInfo.Length]; // Load a filestream and put its content into the byte[] using (System.IO.FileStream fs = fileInfo.OpenRead()) { fs.Read(data, 0, data.Length); } // Delete the temporary file fileInfo.Delete(); prms.Add("type", "photo"); prms.Add("caption", body); prms.Add("source", title); prms.Add("data", data); postUrl = "https://api.tumblr.com/v2/blog/" + Hostname + ".tumblr.com/post"; } KeyValuePair <string, string> LoginDetails = new KeyValuePair <string, string>(accesstoken, accesstokensecret); string result = oAuthTumbler.OAuthData(postUrl, "POST", LoginDetails.Key, LoginDetails.Value, prms); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }
private bool CompareLocalAndRemotePstFiles(string localPath, string remotePath) { bool result = true; System.IO.FileInfo localPST = new System.IO.FileInfo(localPath); System.IO.FileInfo remotePST = new System.IO.FileInfo(remotePath); if (_appSettings.FilesAndFoldersCompressFiles) { System.IO.FileInfo uncompressedPST = new System.IO.FileInfo(System.IO.Path.Combine(remotePST.DirectoryName, "uncompressed_PST.pst")); using (System.IO.FileStream compressedFile = remotePST.OpenRead()) using (System.IO.Stream sourceFile = new System.IO.Compression.GZipStream(compressedFile, System.IO.Compression.CompressionMode.Decompress)) using (System.IO.Stream outputFile = System.IO.File.Create(uncompressedPST.FullName)) { int bufferLength = 1024 * 1024; byte[] buffer = new byte[bufferLength]; int readBytes = 0; while ((readBytes = sourceFile.Read(buffer, 0, bufferLength)) > 0) { outputFile.Write(buffer, 0, readBytes); } } remotePST = uncompressedPST; } if (localPST.Exists && remotePST.Exists && localPST.Length == remotePST.Length) { using (System.IO.FileStream localStream = localPST.OpenRead()) { using (System.IO.FileStream remoteStream = remotePST.OpenRead()) { int currentPosition = 0; int bytesRead = 0; byte[] localBytes = new byte[10240]; byte[] remoteBytes = new byte[10240]; do { bytesRead = localStream.Read(localBytes, 0, 10240); remoteStream.Read(remoteBytes, 0, 10240); if (!CompareArrays(localBytes, remoteBytes)) { result = false; } currentPosition += bytesRead; } while (currentPosition < localStream.Length); } } } else { result = false; } if (_appSettings.FilesAndFoldersCompressFiles) { remotePST.Delete(); } return(result); }
private void WriteLogging(string message) { try { if (LoggingEnabled) { string logFileName = ""; if (MonitorPackPath != null && MonitorPackPath.Length > 0) { logFileName = System.IO.Path.GetFileNameWithoutExtension(MonitorPackPath); } else { logFileName = Name; } if (System.IO.Directory.Exists(LoggingPath)) { loggingFileName = System.IO.Path.Combine(LoggingPath, logFileName + DateTime.Now.Date.ToString("yyyyMMdd") + ".log"); string output = new string('*', 80) + "\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + message + "\r\n"; lock (loggingSyncLock) { System.IO.File.AppendAllText(loggingFileName, output); } //Logging files clearups if (lastLoggingCleanupEvent.AddMinutes(1) < DateTime.Now) { List <string> filesCleared = new List <string>(); foreach (string fileName in System.IO.Directory.GetFiles(LoggingPath, logFileName + "*.log")) { System.IO.FileInfo fi = new System.IO.FileInfo(fileName); if (fi.LastWriteTime.AddDays(LoggingKeepLogFilesXDays) < DateTime.Now) { filesCleared.Add(fi.FullName); fi.Delete(); } } lastLoggingCleanupEvent = DateTime.Now; foreach (string fileName in filesCleared) { WriteLogging(string.Format("The logging file '{0}' has been deleted because it is older than {1} days.", fileName, LoggingKeepLogFilesXDays)); } } } else { RaiseMonitorPackError(string.Format("The LoggingPath '{0}' does not exist!", LoggingPath)); } } } catch (Exception ex) { RaiseMonitorPackError(string.Format("Error performing WriteLogging: {0}", ex.Message)); } }
private void DeleteLogFileIfBig() { // Deletes log file when it exists and is big enough. if (logFileInfo.Exists && logFileInfo.Length > Configuration.AppConfig.LOG_FILE_SIZE_LIMIT) { logFileInfo.Delete(); } }
/// 删除文件文件或图片 /// </summary> /// <param name="path">当前文件的路径</param> /// <returns>是否删除成功</returns> public static void FilePicDelete(string path) { System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { file.Delete(); } }
/// <summary> /// 清除缓存,即删除文件 /// </summary> /// <param name="key">文件路径</param> public static void Remove(string key) { System.IO.FileInfo file = new System.IO.FileInfo(key); if (file.Exists) { file.Delete(); } }
public static void DeletePDF(File file) { //Delete the old file System.IO.FileInfo oldFile = new System.IO.FileInfo(FilePath + file.ID.ToString()); oldFile.Delete(); FileBLL.Remove(file); }
public ActionResult DeleteConfirmed(int id) { Banner banner = db.Banners.Find(id); System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath(banner.Img)); fi.Delete(); db.Banners.Remove(banner); db.SaveChanges(); return RedirectToAction("Index"); }
public void logFunctionCreateTXTLogFile() { System.IO.FileInfo fi = new System.IO.FileInfo(filePath + "\\log.txt"); fi.Delete(); logger.log(LogLevel.Debug, "First record after delete file"); Assert.IsTrue(fi.Exists); }
/// <summary> /// 删除文件 /// </summary> /// <param name="path">路径</param> public void DeteleFile(string path) { path = System.Web.HttpContext.Current.Server.MapPath("~" + path); System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { file.Delete(); } }
/// <summary> /// Removes the object from the vault. /// </summary> /// <param name="name">The name of the object</param> public void RemoveFile(string name) { System.IO.FileInfo finfo = new System.IO.FileInfo(vaultDirectory + "\\" + name + extension); if (finfo.Exists) { finfo.Delete(); } }
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 Delete() { if (!Validation.CanWrite(innerInfo.FullName, false)) { DebugConsole.ThrowError($"Cannot delete file \"{Name}\": modifying the files in this folder/with this extension is not allowed."); return; } innerInfo.Delete(); }
public void Delete() { if (!Validation.CanWrite(innerInfo.FullName)) { DebugConsole.ThrowError($"Cannot delete file \"{Name}\": failed validation"); return; } innerInfo.Delete(); }
public override void DoEvent(FileManager fm) { Classes.MyDisk d = fm.dataHolder.Select(DeviceId, DiskId); var f = d.files.Find((x) => { return(x.FilePath == this.Path); }); d.files.Remove(f); System.IO.FileInfo fi = new System.IO.FileInfo(FileManager.PathToHFOFolder + this.InfoFilePath); fi.Delete(); fm.dataHolder.devices.Find((x) => { return(x.Id == this.DeviceId); }).RewriteDeviceFile(); }
public void Delete(string fileName) { var prefix = fileName.Substring(0, 2); var file = new System.IO.FileInfo(System.IO.Path.Combine(this.RootPath, prefix, fileName)); if (file.Exists) { file.Delete(); } }
/* * <summary> * remove the file * </summary> */ public void DeleteFile() { try { _fileName.Delete(); } catch (System.IO.IOException ex) { throw new System.IO.IOException(ex.Message + " - DeleteFile"); } catch (UnauthorizedAccessException ex) { throw new UnauthorizedAccessException(ex.Message + " - DeleteFile"); } catch (System.Security.SecurityException ex) { throw new System.Security.SecurityException(ex.Message + " - DeleteFile"); } }
static void Main(string[] args) { //try { System.IO.FileInfo fi = new System.IO.FileInfo("somefile"); fi.Delete(); Console.WriteLine("Calling Delete() did not throw"); //} catch (System.IO.IOException e) { //Console.WriteLine(e.Message); //} }
bool upload_Image(FileUpload fileupload, string ImageSavedPath, out string imagepath) { FileUpload FileUploadControl = fileupload; imagepath = ""; if (fileupload.HasFile) { //string filepath = Server.MapPath(ImageSavedPath); String fileExtension = System.IO.Path.GetExtension(FileUploadControl.FileName).ToLower(); List <string> allowedExtensions = new List <string> { ".xlsx" }; if (allowedExtensions.Contains(fileExtension)) { try { string strMoRongFile = System.IO.Path.GetExtension(FileUploadControl.FileName); string filename = System.IO.Path.GetFileName(FileUploadControl.FileName); string strTenCu = filename; string strTenMoi = string.Format("{0}_{1}_{2}_{3}_{4}_{5}", DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Second, 0, 0, Utils.RemoveUnicode(filename).Replace(" ", "_")); string directoryPath = Server.MapPath("~/NuceDataUpload/cauhoi"); if (!System.IO.Directory.Exists(directoryPath)) { System.IO.Directory.CreateDirectory(directoryPath); } string path = Server.MapPath("~/NuceDataUpload/cauhoi/" + strTenMoi); string strLinkFile = path; System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists)//check file exsit or not { file.Delete(); } FileUploadControl.SaveAs(strLinkFile); strLinkFile = "/NuceDataUpload/cauhoi/" + strTenMoi; imagepath = strLinkFile; } catch (Exception) { imagepath = "File could not be uploaded."; } return(true); } else { imagepath = string.Format("Tệp mở rộng {0} không hỗ trợ ", fileExtension); } } else { imagepath = string.Format("file không upload được"); } return(false); }
private void CreateTempFile(string content) { testFile = new System.IO.FileInfo("webdriver.tmp"); if (testFile.Exists) { testFile.Delete(); } System.IO.StreamWriter testFileWriter = testFile.CreateText(); testFileWriter.WriteLine(content); testFileWriter.Close(); }
public override int Delete(long ID) { string path = BuildFilePath(ID); System.IO.FileInfo fi = new System.IO.FileInfo(path); if (fi.Exists) { fi.Delete(); return 1; } return 0; }
private bool DeleteFile(string path, HttpContext context) { bool ret = false; System.IO.FileInfo file = new System.IO.FileInfo(context.Server.MapPath(path)); if (file.Exists) { file.Delete(); ret = true; } return ret; }
/// <summary> /// 删除文件文件或图片 /// </summary> /// <param name="path">当前文件的路径 </param> /// <returns>是否删除成功 </returns> public void DeleteFile(string path) { path = Server.MapPath(path); //获得文件对象 System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { file.Delete();//删除 } //file.Create();//文件创建方法 }
public void Delete(string path) { System.IO.FileInfo fi = new System.IO.FileInfo(path); try { fi.Delete(); } catch (System.IO.IOException e) { } }
public void SaveAsOfficeOpenXml(string fileName) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); if (fileInfo.Exists) fileInfo.Delete(); ExcelPackage excelPackage = new ExcelPackage(fileInfo); ExcelWorksheet sheet1 = excelPackage.Workbook.Worksheets.Add("Sheet1"); for (int rowInd= 0; rowInd <rows.Count; rowInd++) for (int colInd= 0; colInd<rows[rowInd].Cells.Count; colInd++) sheet1.Cells[rowInd+1, colInd+1].Value = rows[rowInd].Cells[colInd].Value; excelPackage.Save(); }
/// <summary> /// 删除 /// </summary> /// <param name="fileName"></param> public bool fileDelete(string fileName) { string filePath = getFileFullPath(fileName); System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { fileInfo.Delete(); return true; } else { _errorMessage = "文件不存在"; return false; } }
public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); }
protected void btn_move_Click(object sender, EventArgs e) { for (int i = 0; i < GridView2.Rows.Count; i++) { CheckBox cb = new CheckBox(); cb = (CheckBox)GridView2.Rows[i].FindControl("cbSel"); if (cb.Checked) { string name = GridView2.DataKeys[i].Value.ToString().Substring(GridView2.DataKeys[i].Value.ToString().LastIndexOf("/") + 1).ToUpper(); CY.HotelBooking.Core.Business.Web_Xml xml = new CY.HotelBooking.Core.Business.Web_Xml(); string webPath = Server.MapPath("~/ADIMG/"); System.IO.FileInfo file = new System.IO.FileInfo(webPath + name); file.Delete(); xml.DeleteElement(webPath, "~/ADIMG/" + name); } } string tablename = IMGType.SelectedItem.Value; dataBind(tablename); GridView2.DataBind(); }
protected void btm_export_dsd_Click(object sender, EventArgs e) { try { string s_filename = ((SDMX_Dataloader.Engine.Client)HttpContext.Current.Session[UserDef.UserSessionKey]).FileToDownload; byte[] data = ISTAT.IO.Utility.FileToByteArray(s_filename); System.IO.FileInfo fInfo = new System.IO.FileInfo(s_filename); fInfo.Delete(); ((SDMX_Dataloader.Engine.Client)HttpContext.Current.Session[UserDef.UserSessionKey]).FileToDownload = string.Empty; Response.Clear(); Response.ContentType = "application/zip"; Response.AppendHeader("Content-Disposition", "Attachment; Filename=\"" + fInfo.Name + "\""); Response.OutputStream.Write(data, 0, data.Length); Response.OutputStream.Flush(); } catch { } }
protected void Page_Load(object sender, EventArgs e) { string filename = Request.QueryString.Get("archivo"); string pathname = Request.QueryString.Get("path"); if (!String.IsNullOrEmpty(filename)) { String dlDir = pathname; if (pathname == null) { dlDir = @"~/Temp/"; } String path = ""; if (Session["urlDescargaTemporarios"] == null) { path = Server.MapPath(dlDir + filename); } else { object url = Session["urlDescargaTemporarios"]; path = url.ToString() + filename; } System.IO.FileInfo toDownload = new System.IO.FileInfo(path); if (toDownload.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + toDownload.Name); Response.AddHeader("Content-Length", toDownload.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(dlDir + filename); Response.End(); toDownload.Delete(); } else { WebForms.Excepciones.Redireccionar(new EX.Validaciones.ArchivoInexistente(filename), "~/NotificacionDeExcepcion.aspx"); } } }
public ActionResult Build(string id, bool reset = false, string key = null) { string buildPath = IISStore + "\\" + id; string commandLine = id + " \"" + buildPath + "\"" ; string path = IISStore + "\\" + id + "\\build-config.json"; var model = JsonStorage.ReadFile<BuildConfig>(path); if (!string.IsNullOrWhiteSpace(key)) { if (model.TriggerKey != key) throw new UnauthorizedAccessException(); } if (reset) { var file = new System.IO.FileInfo(buildPath + "\\local-repository.json"); if (file.Exists) { file.Delete(); } } return new BuildActionResult(model,commandLine); }
protected void Page_Load(object sender, EventArgs e) { string filename = Request.QueryString.Get("archivo"); if (!String.IsNullOrEmpty(filename)) { String dlDir = @"~/Temp/"; String path = Server.MapPath(dlDir + filename); System.IO.FileInfo toDownload = new System.IO.FileInfo(path); if (toDownload.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + toDownload.Name); Response.AddHeader("Content-Length", toDownload.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(dlDir + filename); Response.End(); toDownload.Delete(); } else { CedeiraUIWebForms.Excepciones.Redireccionar(new Microsoft.ApplicationBlocks.ExceptionManagement.Archivo.ArchivoInexistente(filename), "~/Excepcion.aspx"); } } }
private void deleteFileEx(string path) { string strFolder = txtFolder.Text; string fullpath = "../" + strFolder + "/" + path; fullpath = Server.MapPath(fullpath); try { System.IO.FileInfo Fi = new System.IO.FileInfo(fullpath); if (Fi.Exists) { Fi.Delete(); } } catch (Exception ex) { Alert(ex); } }
public static void CheckLogFileSize() { try { System.IO.FileInfo fi = new System.IO.FileInfo(LogFileName); if (fi.Exists && fi.Length > MAX_LOG_FILE_SIZE) { fi.Delete(); _debugQueue.Enqueue(string.Format("LOG FILE CLEARED *** FILE SIZE WAS {0}bytes", fi.Length)); } } catch { } }
public void ShouldBeAbleToSendKeysToAFileUploadInputElementInAnXhtmlDocument() { // IE before 9 doesn't handle pages served with an XHTML content type, and just prompts for to // download it if (TestUtilities.IsOldIE(driver)) { return; } driver.Url = xhtmlFormPage; IWebElement uploadElement = driver.FindElement(By.Id("file")); Assert.AreEqual(string.Empty, uploadElement.GetAttribute("value")); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); }
private static void Cleanup(Context context) { if (hasCleaned) return; hasCleaned = true; try { var baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); var files = System.IO.Directory.GetFiles(baseDir); if (files == null || files.Length <= 0) return; foreach (var file in files) { if (!file.EndsWith(".urlimage")) continue; var f = new System.IO.FileInfo(file); if (DateTime.UtcNow > f.LastWriteTimeUtc) f.Delete(); } } catch { } }
public JsonResult DeleteVendorDocument(Guid vendorDocumentId, Guid documentId, string fileName) { bool result = false; string StorageFolder = System.Web.HttpContext.Current.Server.MapPath("~/Storage/VendorDocument/"); string fullFileName = System.IO.Path.Combine(StorageFolder, fileName); //FileName => [email protected] if (System.IO.File.Exists(fullFileName)) { try { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fullFileName); fileInfo.Delete(); using (this.UoW) { UoW.Document.Delete(documentId); UoW.VendorDocument.Delete(vendorDocumentId); result = this.UoW.Commit() > 0; } return Json(new { Success = result }); } catch (Exception e) { //throw; } } return Json(new { Success = result }); }
protected void ExportCSVButton_Click(object sender, EventArgs e) { string strReportHtml = string.Empty; try { ExcelManager objExcelManager = new ExcelManager(); //string strParametersPath = this.Page.Server.MapPath("../Reports/Templates/"); // Pass the data and get the path for generated temporary file. // DataTable vdtData, string vstrfilePath, string vstrExportCaption, string vstrDBColumn, string vstrExcelColumn) if (null != ViewState["DataId"]) { string strRand = ViewState["DataId"].ToString(); if (null != this.Page.Session[strRand]) { DataTable dt = this.Page.Session[strRand] as DataTable; if ((null != dt) & (string.IsNullOrEmpty(ExportTemplatePath) == false) && (string.IsNullOrEmpty(ExportTemplate) == false) && (string.IsNullOrEmpty(DBColumn) == false) & (string.IsNullOrEmpty(ExcelColumn) == false)) { /*string strFilePath = objExcelManager.GenerateExcelDataFileFromGrid(dt, this.Page.Server.MapPath(ExportTemplatePath), ExportTemplate, ExportCaption, DBColumn, ExcelColumn, ExcelHeaderRow, StartRow, StartColumn, MaxLevel, SheetNumber, CurrentDateRow, CurrentDateCol, StartDateRow, StartDateCol, EndDateRow, EndDateCol, ReportStartDate, ReportEndDate);*/ string strFilePath = objExcelManager.GenerateCSVFileFromGrid(dt, this.Page.Server.MapPath(ExportTemplatePath), ExportTemplate, ExportCaption, DBColumn, ExcelColumn, ExcelHeaderRow, StartRow, StartColumn, MaxLevel, SheetNumber, CurrentDateRow, CurrentDateCol, StartDateRow, StartDateCol, EndDateRow, EndDateCol, ReportStartDate, ReportEndDate); System.IO.FileInfo objfInfo = new System.IO.FileInfo(strFilePath); if (objfInfo.Exists) { this.Page.Response.Clear(); string attachment = "attachment; filename=" + objfInfo.Name; this.Page.Response.AddHeader("content-disposition", attachment); //if (vExportType == Constants.ExportType.Excel) //{ this.Page.Response.ContentType = "text/csv"; //} //else //{ // Response.ContentType = "text/csv"; //} this.Page.Response.BinaryWrite(System.IO.File.ReadAllBytes(strFilePath)); objfInfo.Delete(); // Once the file content is written to response stream delete it. //Response.End(); } } } } } catch (Exception ex) { //throw; SendMail.MailMessage("ExcelPackage > Error > ExportCSVButton_Click(object sender, EventArgs e)", ex.ToString()); } finally { this.Page.Response.End(); } }
/// <summary>Initializes the directory to create a new file with the given name. /// This method should be used in {@link #createOutput}. /// </summary> protected internal void InitOutput(System.String name) { EnsureOpen(); CreateDir(); System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)); if (file.Exists) // delete existing, if any { try { file.Delete(); } catch (Exception) { throw new System.IO.IOException("Cannot overwrite: " + file); } } }
/// <summary>Removes an existing file in the directory. </summary> public override void DeleteFile(System.String name) { EnsureOpen(); System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name)); try { file.Delete(); } catch (Exception) { throw new System.IO.IOException("Cannot delete " + file); } }
public void UploadingFileShouldFireOnChangeEvent() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); IWebElement result = driver.FindElement(By.Id("fileResults")); Assert.AreEqual(string.Empty, result.Text); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); // Shift focus to something else because send key doesn't make the focus leave driver.FindElement(By.TagName("body")).Click(); inputFile.Delete(); Assert.AreEqual("changed", result.Text); }
public byte[] GetDataToExportCareTeamSurvey(CareTeamSurvey careTeamSurvey, HospitalDetailsDto hospitalDetails) { string fileName = @"C:\Escalation_CareTeam_Report_" + Guid.NewGuid() + ".xlsx"; var configureCells = new ConfigureEscalationReport(); var workbook = new XLWorkbook(); var worksheet = workbook.Worksheets.Add("Survey Escalation Report"); configureCells.ConfigureCell(worksheet,careTeamSurvey.Survey.SurveyType); #region Headers worksheet.Cell("A1").Value = "Survey Type"; worksheet.Cell("B1").Value = "Region"; worksheet.Cell("C1").Value = "Site"; worksheet.Cell("D1").Value = "Site #"; worksheet.Cell("E1").Value = "Date of Survey"; worksheet.Cell("F1").Value = careTeamSurvey.Question3A.QuestionText; worksheet.Cell("G1").Value = careTeamSurvey.Question3B.QuestionText; worksheet.Cell("H1").Value = careTeamSurvey.Question3C.QuestionText; worksheet.Cell("I1").Value = careTeamSurvey.Question3D.QuestionText; worksheet.Cell("J1").Value = careTeamSurvey.Question3E.QuestionText; worksheet.Cell("K1").Value = careTeamSurvey.Question3F.QuestionText; worksheet.Cell("L1").Value = careTeamSurvey.Question3G.QuestionText; worksheet.Cell("M1").Value = careTeamSurvey.Question3H.QuestionText; worksheet.Cell("N1").Value = careTeamSurvey.Question3I.QuestionText; worksheet.Cell("O1").Value = careTeamSurvey.Question3J.QuestionText; worksheet.Cell("P1").Value = careTeamSurvey.Question3K.QuestionText; worksheet.Cell("Q1").Value = careTeamSurvey.Question3L.QuestionText; worksheet.Cell("R1").Value = careTeamSurvey.Question3M.QuestionText; worksheet.Cell("S1").Value = careTeamSurvey.Question3N.QuestionText; worksheet.Cell("T1").Value = careTeamSurvey.Question3O.QuestionText; worksheet.Cell("U1").Value = careTeamSurvey.Question3Why.QuestionText; #endregion #region Rows // write some values into column 2 worksheet.Cell("A2").Value = "Care Team"; worksheet.Cell("B2").Value = hospitalDetails.RegionName; worksheet.Cell("C2").Value = careTeamSurvey.Survey.FacilityName; worksheet.Cell("D2").Value = hospitalDetails.SiteNumber; worksheet.Cell("E2").Value = DateTime.Now.ToString("MM/dd/yyyy"); worksheet.Cell("F2").Value = careTeamSurvey.Question3A.Response; worksheet.Cell("G2").Value = careTeamSurvey.Question3B.Response; worksheet.Cell("H2").Value = careTeamSurvey.Question3C.Response; worksheet.Cell("I2").Value = careTeamSurvey.Question3D.Response; worksheet.Cell("J2").Value = careTeamSurvey.Question3E.Response; worksheet.Cell("K2").Value = careTeamSurvey.Question3F.Response; worksheet.Cell("L2").Value = careTeamSurvey.Question3G.Response; worksheet.Cell("M2").Value = careTeamSurvey.Question3H.Response; worksheet.Cell("N2").Value = careTeamSurvey.Question3I.Response; worksheet.Cell("O2").Value = careTeamSurvey.Question3J.Response; worksheet.Cell("P2").Value = careTeamSurvey.Question3K.Response; worksheet.Cell("Q2").Value = careTeamSurvey.Question3L.Response; worksheet.Cell("R2").Value = careTeamSurvey.Question3M.Response; worksheet.Cell("S2").Value = careTeamSurvey.Question3N.Response; worksheet.Cell("T2").Value = careTeamSurvey.Question3O.Response; worksheet.Cell("U2").Value = careTeamSurvey.Question3Why.Response; #endregion workbook.SaveAs(fileName); var bytes = System.IO.File.ReadAllBytes(fileName); System.IO.FileInfo newFile = new System.IO.FileInfo(fileName); if (newFile.Exists) newFile.Delete(); return bytes; }
/// <summary> /// Dumps the body of this entity into a file /// </summary> /// <param name="path">path of the destination folder</param> /// <param name="name">name of the file</param> /// <returns><see cref="System.IO.FileInfo" /> that represents the file where the body has been saved</returns> public System.IO.FileInfo DumpBody( System.String path, System.String name ) { System.IO.FileInfo file = null; if ( name!=null ) { #if LOG if ( log.IsDebugEnabled ) log.Debug ("Found attachment: " + name); #endif name = System.IO.Path.GetFileName(name); // Dump file contents try { System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo ( path ); dir.Create(); try { file = new System.IO.FileInfo (System.IO.Path.Combine (path, name) ); } catch ( System.ArgumentException ) { file = null; #if LOG if ( log.IsErrorEnabled ) log.Error(System.String.Concat("Filename [", System.IO.Path.Combine (path, name), "] is not allowed by the filesystem")); #endif } if ( file!=null && dir.Exists ) { if ( dir.FullName.Equals (new System.IO.DirectoryInfo (file.Directory.FullName).FullName) ) { if ( !file.Exists ) { #if LOG if ( log.IsDebugEnabled ) log.Debug (System.String.Concat("Saving attachment [", file.FullName, "] ...")); #endif System.IO.Stream stream = null; try { stream = file.Create(); #if LOG } catch ( System.Exception e ) { if ( log.IsErrorEnabled ) log.Error(System.String.Concat("Error creating file [", file.FullName, "]"), e); #else } catch ( System.Exception ) { #endif } bool error = !this.DumpBody (stream); if ( stream!=null ) stream.Close(); stream = null; if ( error ) { #if LOG if ( log.IsErrorEnabled ) log.Error (System.String.Concat("Error writting file [", file.FullName, "] to disk")); #endif if ( stream!=null ) file.Delete(); } else { #if LOG if ( log.IsDebugEnabled ) log.Debug (System.String.Concat("Attachment saved [", file.FullName, "]")); #endif // The file should be there file.Refresh(); // Set file dates if ( this.Header.ContentDispositionParameters.ContainsKey("creation-date") ) file.CreationTime = anmar.SharpMimeTools.SharpMimeTools.parseDate ( this.Header.ContentDispositionParameters["creation-date"] ); if ( this.Header.ContentDispositionParameters.ContainsKey("modification-date") ) file.LastWriteTime = anmar.SharpMimeTools.SharpMimeTools.parseDate ( this.Header.ContentDispositionParameters["modification-date"] ); if ( this.Header.ContentDispositionParameters.ContainsKey("read-date") ) file.LastAccessTime = anmar.SharpMimeTools.SharpMimeTools.parseDate ( this.Header.ContentDispositionParameters["read-date"] ); } #if LOG } else if ( log.IsDebugEnabled ) { log.Debug("File already exists, skipping."); #endif } #if LOG } else if ( log.IsDebugEnabled ) { log.Debug(System.String.Concat ("Folder name mistmatch. [", dir.FullName, "]<>[", new System.IO.DirectoryInfo (file.Directory.FullName).FullName, "]")); #endif } #if LOG } else if ( file!=null && log.IsErrorEnabled ) { log.Error ("Destination folder does not exists."); #endif } dir = null; #if LOG } catch ( System.Exception e ) { if ( log.IsErrorEnabled ) log.Error ("Error writting to disk: " + name, e); #else } catch ( System.Exception ) { #endif try { if ( file!=null ) { file.Refresh(); if ( file.Exists ) file.Delete (); } } catch ( System.Exception ) {} file = null; } } return file; }