Delete() private method

private Delete ( ) : void
return void
    private void ExportChart(string fileName, ISymbolicDataAnalysisSolution solution, string formula) {
      FileInfo newFile = new FileInfo(fileName);
      if (newFile.Exists) {
        newFile.Delete();
        newFile = new FileInfo(fileName);
      }
      var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);

      using (ExcelPackage package = new ExcelPackage(newFile)) {
        ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model");
        FormatModelSheet(modelWorksheet, solution, formulaParts);

        ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset");
        WriteDatasetToExcel(datasetWorksheet, solution.ProblemData);

        ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs");
        WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset);

        if (solution is IRegressionSolution) {
          ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values");
          WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution);

          ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts");
          AddCharts(chartsWorksheet);
        }
        package.Workbook.Properties.Title = "Excel Export";
        package.Workbook.Properties.Author = "HEAL";
        package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab";

        package.Save();
      }
    }
Ejemplo n.º 2
1
        /// <summary>
        /// 保存excel文件,覆盖相同文件名的文件
        /// </summary>
        public static void SaveExcel(string FileName, string sql, string SheetName)
        {

            FileInfo newFile = new FileInfo(FileName);
            if (newFile.Exists)
            {
                newFile.Delete();
                newFile = new FileInfo(FileName);
            }
            using (ExcelPackage package = new ExcelPackage(newFile))
            {
                try
                {
                    ExcelWorksheet ws = package.Workbook.Worksheets.Add(SheetName);

                    IDataReader reader = DBConfig.db.DBProvider.ExecuteReader(sql);
                    ws.Cells["A1"].LoadFromDataReader(reader, true);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                package.Save();
            }
         
        }
            void checksumPackage(ReleaseEntry downloadedRelease)
            {
                var targetPackage = new FileInfo(
                    Path.Combine(rootAppDirectory, "packages", downloadedRelease.Filename));

                if (!targetPackage.Exists) {
                    this.Log().Error("File {0} should exist but doesn't", targetPackage.FullName);

                    throw new Exception("Checksummed file doesn't exist: " + targetPackage.FullName);
                }

                if (targetPackage.Length != downloadedRelease.Filesize) {
                    this.Log().Error("File Length should be {0}, is {1}", downloadedRelease.Filesize, targetPackage.Length);
                    targetPackage.Delete();

                    throw new Exception("Checksummed file size doesn't match: " + targetPackage.FullName);
                }

                using (var file = targetPackage.OpenRead()) {
                    var hash = Utility.CalculateStreamSHA1(file);

                    if (!hash.Equals(downloadedRelease.SHA1,StringComparison.OrdinalIgnoreCase)) {
                        this.Log().Error("File SHA1 should be {0}, is {1}", downloadedRelease.SHA1, hash);
                        targetPackage.Delete();
                        throw new Exception("Checksum doesn't match: " + targetPackage.FullName);
                    }
                }
            }
Ejemplo n.º 4
0
        private static void CreateDeletePackage(int Sheets, int rows)
        {
            List<object> row = new List<object>();
            row.Add(1);
            row.Add("Some text");
            row.Add(12.0);
            row.Add("Some larger text that has completely no meaning.  How much wood can a wood chuck chuck if a wood chuck could chuck wood.  A wood chuck could chuck as much wood as a wood chuck could chuck wood.");

            FileInfo LocalFullFileName = new FileInfo(Path.GetTempFileName());
            LocalFullFileName.Delete();
            package = new ExcelPackage(LocalFullFileName);

            try
            {
                for (int ca = 0; ca < Sheets; ca++)
                {
                    CreateWorksheet("Sheet" + (ca+1), row, rows);
                }

                package.Save();
            }
            finally
            {
                LocalFullFileName.Refresh();
                if (LocalFullFileName.Exists)
                {
                    LocalFullFileName.Delete();
                }

                package.Dispose();
                package = null;

                GC.Collect();
            }
        }
Ejemplo n.º 5
0
        public static FileInfo ToImage(string Html) {
            string wkhtmlPath = Path.Combine(HttpRuntime.AppDomainAppPath, "wkhtmltopdf");
            string svgPath = Path.Combine(HttpRuntime.AppDomainAppPath, "Content", "svg");
            string uid = Guid.NewGuid().ToString();
            FileInfo htmlFi = new FileInfo(Path.Combine(svgPath, string.Format("{0}.html", uid)));
            FileInfo imageFi = new FileInfo(Path.Combine(svgPath, string.Format("{0}.svg", uid)));

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

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

            TextWriter twriter = new StreamWriter(htmlFi.FullName, false, Encoding.UTF8);
            twriter.Write(Html);
            twriter.Dispose();

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
            psi.FileName = Path.Combine(wkhtmlPath, "wkhtmltoimage.exe");
            psi.Arguments = htmlFi.FullName + " " + imageFi.FullName;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

            System.Diagnostics.Process.Start(psi).WaitForExit();
            htmlFi.Delete();

            return imageFi;
        }
        /// <summary>
        /// Executes the tests.
        /// </summary>
        public static void Test()
        {
            TagsTableCollectionIndex index = new TagsTableCollectionIndex();

            // first fill the index.
            ITagCollectionIndexTests.FillIndex(index, 100000);

            // serialize the index.
            FileInfo testFile = new FileInfo(@"test.file");
            testFile.Delete();
            Stream writeStream = testFile.OpenWrite();
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Serializing blocked file....");
            TagIndexSerializer.SerializeBlocks(writeStream, index, 100);
            writeStream.Flush();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testFile.Length / 1024));

            // deserialize the index.
            Stream readStream = testFile.OpenRead();
            ITagsCollectionIndexReadonly readOnlyIndex = TagIndexSerializer.DeserializeBlocks(readStream);

            // test access.
            OsmSharp.Logging.Log.TraceEvent("Blocked", System.Diagnostics.TraceEventType.Information,
                "Started testing random access....");
            ITagCollectionIndexTests.TestRandomAccess("Blocked", readOnlyIndex, 1000);

            readStream.Dispose();
            testFile.Delete();
        }
Ejemplo n.º 7
0
        public void SyncServicePullFileTest()
        {
            Device device = GetFirstDevice();
            FileListingService fileListingService = new FileListingService(device);

            using (ISyncService sync = device.SyncService)
            {
                String rfile = "/sdcard/bootanimations/bootanimation-cm.zip";
                FileEntry rentry = fileListingService.FindFileEntry(rfile);

                String lpath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                String lfile = Path.Combine(lpath, LinuxPath.GetFileName(rfile));
                FileInfo lfi = new FileInfo(lfile);
                SyncResult result = sync.PullFile(rfile, lfile, new FileSyncProgressMonitor());

                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();

                result = sync.PullFile(rentry, lfile, new FileSyncProgressMonitor());
                Assert.IsTrue(lfi.Exists);
                Assert.IsTrue(ErrorCodeHelper.RESULT_OK == result.Code, ErrorCodeHelper.ErrorCodeToString(result.Code));
                lfi.Delete();

            }
        }
Ejemplo n.º 8
0
        private TestAssembly(string assemblyName, string text, IEnumerable<string> referencePaths)
        {
            var path = new FileInfo(Path.Combine(System.IO.Path.GetTempPath(), assemblyName + ".exe"));
            _path = path.FullName;

            if (path.Exists)
            {
                // Don't regenerate if already created for this test run
                if (path.LastWriteTime < DateTime.Now.AddMinutes(-1))
                {
                    path.Delete();
                }
                else
                {
                    return;
                }
            }

            var references = referencePaths.Select(r => MetadataReference.CreateFromFile(r)).ToList();

            var tfm = CSharpSyntaxTree.ParseText(TFM);
            var tree = CSharpSyntaxTree.ParseText(text);
            var compilation = CSharpCompilation.Create(assemblyName, new[] { tree, tfm }, references);
            var result = compilation.Emit(path.FullName);

            if (!result.Success && path.Exists)
            {
                path.Delete();
            }

            Assert.True(result.Success, string.Join("\n", result.Diagnostics
                                                        .Where(d => d.Severity == DiagnosticSeverity.Error)
                                                        .Select(d => d.GetMessage())));
        }
Ejemplo n.º 9
0
 private static void ExtractResources()
 {
     if (resourcesExtracted) {
         return;
     }
     lock (extractResourcesLock) {
         if (resourcesExtracted) {
             return;
         }
         var resourcesPath = GetAbsolutePath("Resources");
         var archives = Directory.EnumerateFiles(resourcesPath, "*.zip", SearchOption.AllDirectories);
         foreach (var archivePath in archives) {
             var destinationPath = Path.GetDirectoryName(archivePath);
             var archive = ZipFile.Open(archivePath, ZipArchiveMode.Read);
             foreach (var archiveEntry in archive.Entries) {
                 var fullEntryPath = Path.Combine(destinationPath, archiveEntry.FullName);
                 var fileInfo = new FileInfo(fullEntryPath);
                 if (fileInfo.Exists) {
                     if (fileInfo.Length != archiveEntry.Length) {
                         fileInfo.Delete();
                     } else if (fileInfo.LastWriteTimeUtc < archiveEntry.LastWriteTime.UtcDateTime) {
                         fileInfo.Delete();
                     }
                 }
                 if (!fileInfo.Exists) {
                     archiveEntry.ExtractToFile(fullEntryPath);
                 }
             }
         }
         resourcesExtracted = true;
     }
 }
Ejemplo n.º 10
0
        private void btnAggiornaDocumentiClick(object sender, EventArgs e)
        {
            var documenti = _daoFactory.GetDocumentoDao().GetAll();
            var aziende = _daoFactory.GetAziendaDao().GetAll();

            var documentFileSystemRespository = ConfigurationManager.AppSettings["fileSystemRepository"];
            foreach (var file in Directory.GetFiles(documentFileSystemRespository))
            {
                var fileInfo = new FileInfo(file);
                var checksum = Gipasoft.Library.Utility.GetFileChecksum(fileInfo);
                var documento = documenti.FirstOrDefault(item => item.Checksum == checksum);
                if(documento == null)
                    fileInfo.Delete();
                else
                {
                    var azienda = aziende.FirstOrDefault(item => item.ID == documento.Azienda.ID);
                    if (azienda != null)
                    {
                        var newPath = documentFileSystemRespository + azienda.Codice;
                        if(!string.IsNullOrEmpty(newPath))
                        {
                            if (!Directory.Exists(newPath))
                                Directory.CreateDirectory(newPath);
                            fileInfo.CopyTo(newPath + @"\" + fileInfo.Name);
                            fileInfo.Delete();
                        }
                    }
                    else
                        fileInfo.Delete();
                }
            }
        }
Ejemplo n.º 11
0
 public void removeAppConfig()
 {
     init();
     if (AppConfigfile.Exists)
     {
         AppConfigfile.Delete();
     }
 }
Ejemplo n.º 12
0
        public static void GenerateReport(bool debugMode)
        {
            DataSet ds = DB.ExecuteStoredProcedure("sp_Report_CorporateInventory");
            string temporaryDirectory = @"C:\Temp";
            string temporaryFileName = string.Format("TrollbeadsInventory-{0:yyyMMdd}.csv", DateTime.Now);
            string temporaryFilePath = Path.Combine(temporaryDirectory, temporaryFileName);
            FileInfo fi = new FileInfo(temporaryFilePath);

            if (fi.Exists)
                fi.Delete();

            CsvExport myExport = new CsvExport();

            foreach(DataRow dr in ds.Tables[0].Rows)
            {
                myExport.AddRow();
                myExport["ProductNumber"] = dr["ProductNumber"];
                myExport["Description"] = dr["Description"];
                myExport["Category"] = dr["Category"];
                myExport["WholesalePrice"] = dr["WholesalePrice"];
                myExport["RetailPrice"] = dr["RetailPrice"];
                myExport["Quantity"] = dr["Quantity"];
            }

            myExport.ExportToFile(temporaryFilePath);

            if (!debugMode)
            {
                Email email = new Email();

                DataSet recipients = DB.ExecuteStoredProcedure("sp_Report_CorporateInventory_EmailRecipients");
                string to = string.Empty;
                string bcc = string.Empty;
                if (recipients != null && recipients.Tables[0].Rows.Count > 0)
                {
                    foreach (DataRow row in recipients.Tables[0].Rows)
                    {
                        string key = string.Format("{0}", row["Key"]);

                        if (key.Equals("reportCorporateInventoryRecipient", StringComparison.InvariantCultureIgnoreCase))
                            to = string.Format("{0}", row["Value"]);

                        if (key.Equals("reportCorporateInventoryRecipientBCC", StringComparison.InvariantCultureIgnoreCase))
                            bcc = string.Format("{0}", row["Value"]);
                    }
                }

                email.Send(to: to, cc: null, bcc: bcc, subject: "Trollbeads Inventory", body: string.Empty, filePathForAttachment: temporaryFilePath);

                fi.Delete();
            }
        }
 public static int Custom(string filename, string data, string pre_fix = null, bool overwrite = false)
 {
     int RetVal = 0;
     lock (_custom) {
         FileInfo fi = new FileInfo ("logs/" + filename);
         StreamWriter sw;
         try {
             if (!Directory.Exists("logs"))
                 Directory.CreateDirectory("logs");
             if (overwrite)
             {
                 fi.Delete();
                 sw = fi.CreateText();
             }
             else
             {
                 if (fi.Exists && !overwrite)
                 {
                     if (fi.Length > Log_Size_Limit)
                     {
                         fi.CopyTo("logs/" + filename + ".bak", true);
                         fi.Delete();
                     }
                 }
                 sw = fi.AppendText();
             }
             if (!fi.Exists)
             {
                 sw.WriteLine(DateTime.Now.ToString() + " - [0] - File Created");
             }
             if (pre_fix != null)
                 sw.WriteLine(pre_fix + DateTime.Now.ToString() + " - " + data);
             else
                 sw.WriteLine (DateTime.Now.ToString () + " - " + data);
             sw.Close ();
             sw.Dispose();
         } catch (UnauthorizedAccessException e) {
             NagiosExtentions.FileAgeCheck.debugOutput.Add("UnauthorizedAccessException caught in QuasarQode.logs: " + e.Message);
             RetVal = 1001;
         } catch (IOException e) {
             NagiosExtentions.FileAgeCheck.debugOutput.Add("IOException caught in QuasarQode.logs: " + e.Message);
             RetVal = 1002;
         }
         catch (Exception e)
         {
             NagiosExtentions.FileAgeCheck.debugOutput.Add("Generic Exception caught in QuasarQode.logs: " + e.Message);
             RetVal = 1003;
         }
     }
     return RetVal;
 }
Ejemplo n.º 14
0
        public void CleanupFiles()
        {
            try
            {
                string path = System.Web.HttpContext.Current.Server.MapPath("~/UploadedImages");
                DirectoryInfo di = new DirectoryInfo(path);
                if (!di.Exists)
                {
                    di.Create();
                }
                var files = di.GetFiles();
                foreach(var f in files)
                {
                    FileInfo fi = new FileInfo(f.FullName);
                    try
                    {
                        fi.Delete();
                    }
                    catch(Exception ex)
                    {
                        logger.WarnFormat("Failed to delete file. Errro:{0}",ex.Message);
                    }
                }


            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }

        }
Ejemplo n.º 15
0
        private void Excluir()
        {
            if (System.IO.File.Exists(@"U:\temp\ArquivoExemplo.txt"))
            {
                // Use a try block to catch IOExceptions, to
                // handle the case of the file already being
                // opened by another process.
                try
                {
                    System.IO.File.Delete(@"U:\temp\ArquivoExemplo.txt");
                }
                catch (System.IO.IOException e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
            }

            // ...or by using FileInfo instance method.
            System.IO.FileInfo fi = new System.IO.FileInfo(@"U:\temp\ArquivoExemplo.txt");
            try
            {
                fi.Delete();
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
            MessageBox.Show("Arquivo Excluido com sucesso!!!");
        }
Ejemplo n.º 16
0
        public void ProcessRequest(HttpContext context)
        {
            string fileURL = context.Request.QueryString["fileurl"];
            string pid = context.Request.QueryString["pid"];
            string iid = context.Request.QueryString["iid"];
            if (CFunctions.IsNullOrEmpty(fileURL)) return;

            if (pid == "0" || (pid != "0" && iid == "0"))
            {
                FileInfo fileInfo = new FileInfo(context.Server.MapPath(fileURL));
                if (fileInfo != null || fileInfo.Exists)
                    fileInfo.Delete();
                context.Response.ContentType = "text/plain";
                context.Response.Write("{\"name\":\"done\"}");
                return;
            }

            if (!CFunctions.IsNullOrEmpty(iid) && iid != "0")
            {
                new CFileattach(CCommon.LANG).Delete(iid);
            }

            context.Response.ContentType = "text/plain";
            context.Response.Write("{\"name\":\"done\"}");
        }
Ejemplo n.º 17
0
        private bool GenerateExcelDocumentF4()
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(@"temp\test.xlsx");
            if (fi.Exists)
            {
                try
                {
                    fi.Delete();
                }
                catch
                {
                    return(false);
                }
            }
            OfficeOpenXml.ExcelPackage xls = new OfficeOpenXml.ExcelPackage(fi);
            var sheet = xls.Workbook.Worksheets.Add("test");

            sheet.Cells["A1"].Value = "F1";
            sheet.Cells["B1"].Value = "F2";
            sheet.Cells["C1"].Value = "F3";
            sheet.Cells["D1"].Value = "F4";
            int    min = 0;
            int    max = 50;
            Random rnd = new Random();

            for (int i = 1; i < _itemsQty + 1; i++)
            {
                sheet.Cells[i + 1, 1].Value = Math.Round(rnd.NextDouble() * (max - min) + min, 2);
                sheet.Cells[i + 1, 2].Value = Math.Round(rnd.NextDouble() * (max - min) + min, 2);
                sheet.Cells[i + 1, 3].Value = Math.Round(rnd.NextDouble() * (max - min) + min, 2);
                sheet.Cells[i + 1, 4].Value = Math.Round(rnd.NextDouble() * (max - min) + min, 2);
            }
            xls.Save();
            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// delete all log files older than daysSaved
        /// </summary>
        internal static void CleanLog(int daysSaved)
        {
            string logpath = Application.StartupPath.ToString() + @"\LOG";

            if (System.IO.Directory.Exists(logpath))
            {
                string[] files = System.IO.Directory.GetFiles(logpath);

                foreach (string s in files)
                {
                    FileInfo fi = new FileInfo(s);

                    if (DateTime.Compare(fi.LastWriteTime, DateTime.Today.Subtract(TimeSpan.FromDays(daysSaved))) < 0)
                    {
                        try
                        {
                            fi.Delete();
                        }
                        catch (System.IO.IOException e)
                        {
                           // WriteLog("CLEAN: " + e.ToString());
                            Debug.WriteLine("CleanLog: " + e.ToString());
                        }
                    }
                }
            }
        }
Ejemplo n.º 19
0
    public void WriteLog(string sErrMsg)
    {
        try
            {
                string sFileName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog.txt";
                System.IO.FileInfo objFileInfo = new System.IO.FileInfo(sFileName);
                if (!objFileInfo.Exists)
                    objFileInfo.Create();

                if (objFileInfo.Length > 10485760)
                {
                    string str_number = Guid.NewGuid().ToString();
                    string newFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "ErrorLog\\" + str_number + "ErrorLog.txt";
                    objFileInfo.CopyTo(newFile);
                    objFileInfo.Delete();
                }

                string sPathName = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "//ErrorLog.txt";//ConfigurationSettings.AppSettings["LogFileName"];

                System.IO.FileStream objFileStream = objFileInfo.Open(System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                System.IO.StreamWriter objWriter = new System.IO.StreamWriter(objFileStream);
                objWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End);
                objWriter.WriteLine("Error Occured at " + DateTime.Now.ToLongDateString() + " : " + DateTime.Now.ToLongTimeString());
                objWriter.WriteLine(sErrMsg);
                objWriter.WriteLine("----------------------------------------------------------------------");
                objWriter.Close();
            }
            catch { }
    }
Ejemplo n.º 20
0
    public void deleteDir(string root, string output)
    {
        //  by using FileInfo instance method.
        System.IO.FileInfo fi = new System.IO.FileInfo(output);
        try
        {
            fi.Delete();
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }

        // ...or with DirectoryInfo instance method.

        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(root);
        // Delete this dir and all subdirs.
        try
        {
            di.Delete(true);
        }
        catch (System.IO.IOException e)
        {
            Console.WriteLine(e.Message);
        }
    }
Ejemplo n.º 21
0
        private double CompressionTest(int[] RandomNumberAr, int MinBorder, int MaxBorder)
        {
            FileInfo     tempFile = new System.IO.FileInfo(@"..\..\temp.bin");
            StreamWriter writer   = tempFile.AppendText();

            foreach (int number in RandomNumberAr)
            {
                writer.Write((char)number);
            }
            writer.Close();

            ProcessStartInfo psi = new ProcessStartInfo(@"..\..\lzma.exe");

            psi.RedirectStandardOutput = true;
            psi.UseShellExecute        = false;
            psi.WindowStyle            = ProcessWindowStyle.Hidden;
            psi.CreateNoWindow         = true;
            psi.StandardOutputEncoding = Encoding.GetEncoding(866);
            psi.Arguments = @"e ""..\..\temp.bin"" ""..\..\temp.lzma"" -d16 -lc0";
            Process task = Process.Start(psi);

            while (!task.HasExited)
            {
                Thread.Sleep(100);
            }

            FileInfo compressedTempFile = new System.IO.FileInfo(@"..\..\temp.lzma");

            double ratio = (double)compressedTempFile.Length / tempFile.Length;

            tempFile.Delete();
            compressedTempFile.Delete();

            return(ratio);
        }
        protected void gvUploadFiles_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                try
                {
                    string StoredFileName = e.CommandArgument.ToString();

                    BEStudent objBEStudent = new BEStudent();
                    BStudent  objBStudent  = new BStudent();
                    objBEStudent.IntTransID = Convert.ToInt64(Request.QueryString["TransID"]);

                    objBEStudent.strOriginalFileName = StoredFileName;

                    System.IO.FileInfo objFileName = new System.IO.FileInfo(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["StudentUploads"]) + "\\" + StoredFileName);

                    if (objFileName.Exists)
                    {
                        objFileName.Delete();
                        objBStudent.BStudentDeleteUploadedFile(objBEStudent);
                    }
                    else
                    {
                        //ScriptManager.RegisterStartupScript(this, this.GetType(), "NotSaved", "alert('File doesnot exist');", true);

                        Page.ClientScript.RegisterStartupScript(GetType(), "MyScript", "alert('File deletion failed.Please try again.');", true);
                    }
                    gvUploadFiles.Rebind();
                    trMessage.Visible = false;
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 23
0
        protected void btnXoaAnh_Click(object sender, EventArgs e)
        {
            AnhDAL _dalanh   = new AnhDAL();
            string SqlUpdate = string.Empty;

            foreach (DataListItem m_Item in dgrListImages.Items)
            {
                int _ID = int.Parse(this.dgrListImages.DataKeys[m_Item.ItemIndex].ToString());

                CheckBox chk_Select   = (CheckBox)m_Item.FindControl("optSelect");
                Label    lbFileAttach = m_Item.FindControl("lbFileAttach") as Label;
                if (chk_Select != null && chk_Select.Checked)
                {
                    _dalanh.DeleteFromT_Anh(_ID);
                    string             path = HttpContext.Current.Server.MapPath("/" + System.Configuration.ConfigurationManager.AppSettings["viewimg"].ToString() + lbFileAttach.Text);
                    System.IO.FileInfo fi   = new System.IO.FileInfo(path);
                    try
                    {
                        if (File.Exists(path))
                        {
                            fi.Delete();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            LoadDataImage();
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 验证木马
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static bool IsAllowedExtension(string filePath)
        {
            bool result = false;

            try
            {
                StreamReader sr         = new StreamReader(filePath, System.Text.Encoding.Default);
                string       strContent = sr.ReadToEnd();
                sr.Close();
                string str = "request|.getfolder|.createfolder|.deletefolder|.createdirectory|.deletedirectory|.saveas";
                str += "|eval|wscript.shell|script.encode|server.|.createobject|execute|activexobject|language=";
                foreach (string s in str.Split('|'))
                {
                    if (strContent.IndexOf(s) != -1)
                    {
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.FileInfo fi = new System.IO.FileInfo(filePath);
                            fi.Delete();
                        }
                        return(false);
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                return(false);
            }
            return(result);
        }
Ejemplo n.º 25
0
    protected void btnConnectExcel_Click(object sender, System.EventArgs e)
    {
        if (!this.ValidateExcel(this.fupExcel))
        {
            return;
        }
        string text = base.Server.MapPath(ConfigHelper.Get("TempDirectory"));

        if (!System.IO.Directory.Exists(text))
        {
            System.IO.Directory.CreateDirectory(text);
        }
        this.excelName = text + this.fupExcel.FileName;
        this.ViewState["ExcelName"] = this.excelName;
        this.hfldExcelName.Value    = this.excelName;
        if (System.IO.File.Exists(this.excelName))
        {
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(this.excelName);
            if (fileInfo.IsReadOnly)
            {
                fileInfo.IsReadOnly = false;
            }
            fileInfo.Delete();
        }
        this.fupExcel.SaveAs(this.excelName);
        this.ClearDataAndInitialize();
    }
Ejemplo n.º 26
0
        public async Task <IActionResult> DeleteConfirmed(long id)
        {
            var product = await _context.Products

                          .Include(a => a.IdmenuNavigation)
                          .Where(a => a.Id == id).FirstOrDefaultAsync();

            try
            {
                _context.Products.Remove(product);
                await _context.SaveChangesAsync();

                List <Productdatum> data = await _context.Productdata.Where(po => po.Idproduct == product.Id).ToListAsync();

                try
                {
                    foreach (var i in data)
                    {
                        var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "uploads") + "/product/";
                        var filePath          = Path.Combine(uploadsRootFolder, i.Pathdata);
                        var fileInfo          = new System.IO.FileInfo(filePath);
                        fileInfo.Delete();
                    }
                }
                catch { }
            }
            catch {
                ViewData["messge"] = "این کالا به دلیل موجود اقلام فروشی در سبد خرید امکان حذف ندارد اگر مایل هستید آن را غیر فعال کنید";
                return(View("Delete", product));
            }



            return(Redirect("/Admin/Products/Index"));
        }
Ejemplo n.º 27
0
        public void DeleteOldFile()
        {
            TimeSpan timeSpan   = new TimeSpan(m_nKeepDay, 0, 0, 0);
            DateTime timeDelete = DateTime.Now - timeSpan;

            string[] strAllFiles = System.IO.Directory.GetFiles(m_strDir, "*", System.IO.SearchOption.AllDirectories);

            foreach (string strOnePath in strAllFiles)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(strOnePath);

                if (timeDelete >= fi.CreationTime || timeDelete >= fi.LastWriteTime ||              //)		//지정시간 이전꺼
                    DateTime.Now < fi.CreationTime || DateTime.Now < fi.LastWriteTime)                        //오늘날짜보다 더 큰것.
                {
                    try
                    {
                        fi.Delete();
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine("Delete file Error! ({0})", ex.Message);
                    }
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// 删除x天前创建的文件  2013-03-26 mashanlin 添加<br/>
        /// </summary>
        /// <param name="suffix">文件名中包含</param>
        /// <param name="suffixArray">文件后缀名 如:.rar  .doc</param>
        /// <param name="days">x天前的</param>
        public static void DropFiles(string filepath, string suffix, string[] suffixArray, int days)
        {
            if (filepath == "")
            {
                return;
            }
            string path = "";

            foreach (string p in GetAllDir(filepath, suffixArray))
            {
                path = filepath + p;
                if (!String.IsNullOrEmpty(suffix) && !p.Contains(suffix))
                {
                    continue;
                }

                System.IO.FileInfo f = new System.IO.FileInfo(path);
                if (f.Exists && f.CreationTime < DateTime.Now.AddDays(-(days)))
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                        //Response.Write("<script>alert('删除出错!');                }
                    }
                }
            }
        }
Ejemplo n.º 29
0
    /// <summary>
    /// 文件浏览器使用,浏览指定用户ID的项目,从服务器读取一个文件,保存到"TempFile"目录下
    /// </summary>
    internal bool ReadFileFromServer(string FullPath, int kbyte)//后两项为0
    {
        if (Transport.UserID <= 0)
        {
            return(false);//"您还没有登陆,请先登陆!!";
        }

        string patha = System.Windows.Forms.Application.StartupPath.ToString();

        if (FullPath.IndexOf("\\") != -1)
        {
            FullPath = FullPath.Substring(FullPath.LastIndexOf("\\") + 1);
        }
        string path = patha + "\\TempFile\\" + FullPath;

        try
        {
            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            if (fi.Exists)
            {
                fi.Delete();
            }
        }
        catch { }
        string str = this.TCPDownFile(FullPath, path);

        if (str.StartsWith("Error"))
        {
            return(false);
        }
        else
        {
            return(true);
        }
    }
        private bool renamePicture(string path, string newName)
        {
            bool ret = false;

            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            newName += fi.Extension;
            if (!fi.Exists)
            {
                return(ret);
            }
            string duongdanmoi     = Server.MapPath("~/Asset/Images/");
            string newFilePathName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(duongdanmoi), newName);

            System.IO.FileInfo f2 = new System.IO.FileInfo(newFilePathName);
            try
            {
                if (f2.Exists)
                {
                    f2.Attributes = System.IO.FileAttributes.Normal;
                    f2.Delete();
                }
                fi.CopyTo(newFilePathName);
                fi.Delete();
                ret = true;
            }
            catch
            {
            }
            return(ret);
        }
Ejemplo n.º 31
0
        public void CreateFileTest()
        {
            FileInfo fileToUpload   = new FileInfo(Path.GetTempFileName());
            FileInfo downloadedFile = new System.IO.FileInfo(Path.GetTempFileName());

            // Set the file size
            using (var fstream = fileToUpload.OpenWrite())
            {
                fstream.SetLength(1024 * 1024 * 1);
            }

            dynamic ynode = (JsonConvert.DeserializeObject(yamlOptions) as dynamic);

            IClient sc = Blobstore.CreateClient("dav", ynode["blobstore"]["options"]);

            string objectId = sc.Create(fileToUpload);

            sc.Get(objectId, downloadedFile);

            Assert.IsTrue(fileToUpload.Length == downloadedFile.Length);

            fileToUpload.Delete();
            downloadedFile.Delete();

            //sc.Delete(objectId);
        }
Ejemplo n.º 32
0
        //How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
        //https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/file-system/how-to-copy-delete-and-move-files-and-folders

        //File.Exists Method (String)
        //https://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx

        public void test()
        {
            string curFile = @"c:\temp\test.txt";

            Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

            // Delete a file by using File class static method...
            if (System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
            {
                // Use a try block to catch IOExceptions, to
                // handle the case of the file already being
                // opened by another process.
                try
                {
                    System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
                }
                catch (System.IO.IOException e)
                {
                    Console.WriteLine(e.Message);
                    return;
                }
            }

            // ...or by using FileInfo instance method.
            System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");
            try
            {
                fi.Delete();
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }
        /// <summary>
        /// To rename the snapshot for future refernces
        /// </summary>
        /// <param name="supportId">supportId</param>
        public bool Rename(string supportId)
        {
            string imgName;
            string imgPath = ConfigurationManager.AppSettings["SupportSnapShotPath"];

            imgName = "img_" + supportId + ".png";
            bool ret = false;

            System.IO.FileInfo fi = new System.IO.FileInfo(imgPath);
            if (!fi.Exists)
            {
                return(ret);
            }

            string newFilePathName = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(imgPath), imgName);

            System.IO.FileInfo f2 = new System.IO.FileInfo(newFilePathName);
            try
            {
                if (f2.Exists)
                {
                    f2.Attributes = System.IO.FileAttributes.Normal;
                    f2.Delete();
                }

                fi.CopyTo(newFilePathName);
                fi.Delete();
                ret = true;
            }
            catch
            {
            }

            return(ret);
        }
Ejemplo n.º 34
0
        public async Task <IActionResult> ProductdatasDelete(long id)
        {
            var postdata = await _context.Productdata.FindAsync(id);

            _context.Productdata.Remove(postdata);
            await _context.SaveChangesAsync();

            //File
            try
            {
                var uploadsRootFolder = Path.Combine(_environment.WebRootPath, "uploads") + "/product/";
                var filePath          = Path.Combine(uploadsRootFolder, postdata.Pathdata);
                var fileInfo          = new System.IO.FileInfo(filePath);

                fileInfo.Delete();


                if (postdata.Iddatatype == (int)TypsImgesize.imgepluse)
                {
                    var uploadsRootFolder1 = Path.Combine(_environment.WebRootPath, "uploads") + "/product/";
                    var filePath1          = Path.Combine(uploadsRootFolder, "350_" + postdata.Pathdata);
                    var fileInfo1          = new System.IO.FileInfo(filePath1);

                    fileInfo1.Delete();
                }
            }
            catch { }

            return(Redirect("/Admin/Products/ProductDataIndex/" + postdata.Idproduct));
        }
Ejemplo n.º 35
0
        // remove file from directory. Takes first argument from command line and


        /// <summary>
        /// Deletes the file the user selects
        /// </summary>
        /// <param name="HostName"></param>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <param name="FileToDelete"></param>

        public void DeleteFile(string HostName, string UserName, string Password, string FileToDelete)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format($"ftp://{HostName}" + $"/{FileToDelete}")));

            request.Credentials = new NetworkCredential(UserName, Password);
            request.Method      = WebRequestMethods.Ftp.DeleteFile;

            System.IO.FileInfo file = new System.IO.FileInfo(FileToDelete);
            try
            {
                if (File.Exists(FileToDelete))
                {
                    file.Delete();
                    Console.WriteLine("\nProcess complete: \"" + FileToDelete + "\" deleted");
                }
                else
                {
                    Console.WriteLine("file not found");
                }
            }
            catch (System.IO.IOException e)
            {
                Console.WriteLine("{0} is not a valid file or directory.", e);
            }
        }
Ejemplo n.º 36
0
		private void Rollover()
		{
			this.Close();
			FileInfo fileInfo = new FileInfo(base.FileName);
			if (this.maxSizeRollBackups == 0)
			{
				fileInfo.Delete();
			}
			else
			{
				FileInfo fileInfo2 = new FileInfo(base.FileName + "." + this.maxSizeRollBackups);
				if (fileInfo2.Exists)
				{
					fileInfo2.Delete();
				}
				for (int i = this.maxSizeRollBackups - 1; i > 0; i--)
				{
					fileInfo2 = new FileInfo(base.FileName + "." + i);
					if (fileInfo2.Exists)
					{
						fileInfo2.MoveTo(base.FileName + "." + (i + 1));
					}
				}
				fileInfo.MoveTo(base.FileName + ".1");
			}
			base.Open();
		}
Ejemplo n.º 37
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["align"] != null)
            {
                try { ddlAlignment.SelectedValue = Request.QueryString["align"].ToString(); }
                catch (Exception exception)
                {
                    LogException(exception);
                }
            }

            strControl = "";
            if (Request.QueryString["control"] != null)
            {
                strControl = Request.QueryString["control"];
            }
            if (Request.Form["hdnFile"] != null && Request.Form["hdnFile"] != "")
            {
                string             strDelete   = Request.Form["hdnFile"].ToString().Replace("/", "\\");
                System.IO.FileInfo oFileDelete = new System.IO.FileInfo(Request.PhysicalApplicationPath + strDelete.Substring(1));
                if (oFileDelete.Exists == true)
                {
                    oFileDelete.Delete();
                }
                Response.Redirect(Request.Path + "?type=" + Request.QueryString["type"] + (strControl == "" ? "" : "&control=" + strControl));
            }
            btnInsert.Attributes.Add("onclick", "return btnInsert_Click('" + strControl + "')");
            btnDelete.Attributes.Add("onclick", "return btnDelete_Click();");
            btnClose.Attributes.Add("onclick", "return window.top.HidePanel();");
            LoadTree();
        }
        /// <summary>
        /// Delete a file that has been processed successfully.
        /// </summary>
        /// <param name="processingFile">File to process</param>
        public void Handle(ProcessingFile processingFile)
        {
            var file = new FileInfo(processingFile.CurrentFilePath);
            if (file.Exists)
            {
                file.Delete();
            }

            const int MaxTries = 10;
            var tries = 0;
            Exception lastException;
            do
            {
                tries++;
                try
                {
                    File.Delete(processingFile.CurrentFilePath);
                    Logger.InfoFormat("Deleted: {0}", processingFile.CurrentFilePath);
                    return;
                }
                catch (IOException ex)
                {
                    lastException = ex;

                    Logger.InfoFormat(
                        "Failed deleting {0} - attempt {1}/{2}", processingFile.CurrentFilePath, tries, MaxTries);
                    Thread.Sleep(1000);
                }
            }
            while (tries < MaxTries);

            throw new FileDeleteException(processingFile.CurrentFilePath, lastException);
        }
Ejemplo n.º 39
0
        private static void ExportExcel_Exit(string filename, Workbook workbook, Application m_xlApp, Worksheet wksheet)
        {
            try
            {
                System.IO.FileInfo path = new System.IO.FileInfo(filename);
                workbook.SaveAs(filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                workbook.Close(Type.Missing, Type.Missing, Type.Missing);
                m_xlApp.Workbooks.Close();
                m_xlApp.Quit();
                m_xlApp.Application.Quit();
                CloseExeclProcess(m_xlApp);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(wksheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(m_xlApp);

                wksheet  = null;
                workbook = null;
                m_xlApp  = null;

                GC.Collect();
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Charset         = "GB2312";
                System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpContext.Current.Server.UrlEncode(filename));
                System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel"; // 指定返回的是一个不能被客户端读取的流,必须被下载

                System.Web.HttpContext.Current.Response.WriteFile(filename);                  // 把文件流发送到客户端
                System.Web.HttpContext.Current.Response.Flush();
                path.Delete();                                                                //删除服务器文件
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        private string UploadedImageFile(IFormFile _HttpFile, string OldFile)
        {
            string uniqueFileName = null;
            string DelMainImage   = OldFile;

            if (_HttpFile != null)
            {
                var    allowedExtensions = new[] { ".jpeg", ".png", ".gif", ".jpg", ".pdf", ".doc", ".xlsx", ".txt" };
                string picExtenction     = System.IO.Path.GetExtension(_HttpFile.FileName.ToLower());

                string uploadsFolder = System.IO.Path.Combine(webHostEnvironment.WebRootPath, "img/app-images");
                uniqueFileName = "Image_" + Guid.NewGuid().ToString() + picExtenction;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);

                if (DelMainImage != null)
                {
                    string             DelPath = System.IO.Path.Combine(uploadsFolder, DelMainImage);
                    System.IO.FileInfo DelFile = new System.IO.FileInfo(DelPath);
                    if (DelFile.Exists)
                    {
                        DelFile.Delete();
                    }
                }

                if (allowedExtensions.Contains(picExtenction))
                {
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        _HttpFile.CopyTo(fileStream);
                    }
                }
            }
            return(uniqueFileName);
        }
Ejemplo n.º 41
0
        public static void Saveplayers(string path, List <Player> playerList, Player currentplayer)
        {
            //playerList.Find(x => x.UserName.ToLower() == currentplayer.UserName.ToLower()) = currentplayer;

            Type[] types = Types();

            System.IO.FileInfo fi = new System.IO.FileInfo(path);
            if (!fi.Directory.Exists)
            {
                fi.Directory.Create();
            }

            if (fi.Exists)
            {
                fi.Delete();
            }
            try
            {
                StreamWriter w = new StreamWriter(path);

                XmlSerializer xmlserializer = new XmlSerializer(typeof(List <Player>), types);
                xmlserializer.Serialize(w, playerList);

                w.Close();
            }
            catch (Exception exp)
            {
                System.Windows.Forms.MessageBox.Show(exp.Message);
            }
            finally { }
        }
Ejemplo n.º 42
0
        void resetBeforeExit()
        {
            Log.Info("resetBeforeExit");
            if (download != null)
            {
                download.Dispose();
            }
            if (jpgToDelete && convertedJpg != "")
            {
                System.IO.FileInfo file = new System.IO.FileInfo(convertedJpg);
                file.Delete();
            }

            download = null;
            SetVisible(false);
            GUI.enabled   = false;
            downloadState = downloadStateType.INACTIVE;
            RemoveInputLock();

            cfgWinData        = false;
            m_fileBrowser     = null;
            m_textPath        = "";
            craftURL          = "";
            newCraftName      = "";
            saveInSandbox     = false;
            saveInVAB         = false;
            saveInSPH         = false;
            saveInShipDefault = true;
            overwriteExisting = false;
            loadAfterImport   = true;
            subassembly       = false;
            CIInfoDisplay.infoDisplayActive = false;
        }
Ejemplo n.º 43
0
        public static void ExportToFolder(string fullFileNameA, List <Player> playerList)
        {
            Type[] types = Types();

            System.IO.FileInfo fiA = new System.IO.FileInfo(fullFileNameA);
            if (!fiA.Directory.Exists)
            {
                fiA.Directory.Create();
            }

            if (fiA.Exists)
            {
                fiA.Delete();
            }
            try
            {
                StreamWriter w = new StreamWriter(fullFileNameA);

                XmlSerializer xmlserializer = new XmlSerializer(typeof(List <Player>), types);
                xmlserializer.Serialize(w, playerList);

                w.Close();
            }
            catch (Exception exp)
            {
                System.Windows.Forms.MessageBox.Show(exp.Message + exp.InnerException.Message);
            }
            finally { }
        }
Ejemplo n.º 44
0
        public void replaceDB()
        {
            //replace DB
            System.IO.FileInfo fi  = new System.IO.FileInfo(SharedVar.dbpath);
            System.IO.FileInfo fin = new System.IO.FileInfo(SharedVar.newDbPath);
            System.IO.FileInfo fib = new System.IO.FileInfo(SharedVar.bkDbPath);
            try
            {
                if (fib.Exists)
                {
                    fib.Delete();
                    Console.WriteLine("ex bk deleted.");
                }
                if (fi.Exists)
                {
                    GC.Collect();
                    // GC.WaitForPendingFinalizers();

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

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

                    Console.WriteLine("Update ok.");
                }
            }
            catch
            {
            }
//            File.Replace(SharedVar.newDbPath, SharedVar.dbpath, SharedVar.bkDbPath);
        }
Ejemplo n.º 45
0
        private void BtnDel_Click(object sender, EventArgs e)
        {
            if (dataGridViewLeaveMsgs.SelectedRows.Count > 0)
            {
                using (var db = new ICMDBContext())
                {
                    var LeaveMsgs = (from DataGridViewRow row in dataGridViewLeaveMsgs.SelectedRows
                                     select(db.Leavewords.Attach(row.DataBoundItem as leaveword))).ToList();

                    db.Leavewords.RemoveRange(LeaveMsgs);
                    db.SaveChanges();
                }
                System.IO.FileInfo fiSdp   = new System.IO.FileInfo(m_filename + ".sdp");
                System.IO.FileInfo fiRtpaD = new System.IO.FileInfo(m_filename + ".rtpa.data");
                System.IO.FileInfo fiRtpaI = new System.IO.FileInfo(m_filename + ".rtpa.index");
                System.IO.FileInfo fiRtpvD = new System.IO.FileInfo(m_filename + ".rtpv.data");
                System.IO.FileInfo fiRtpvI = new System.IO.FileInfo(m_filename + ".rtpv.index");
                try
                {
                    fiSdp.Delete();
                    fiRtpaD.Delete();
                    fiRtpaI.Delete();
                    fiRtpvD.Delete();
                    fiRtpvI.Delete();
                }
                catch { }
                RefreshLeaveMsgsGridView();
            }
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Copy the specified file.
        /// </summary>
        ///
        /// <param name="source">The file to copy.</param>
        /// <param name="target">The target of the copy.</param>
        public static void CopyFile(FileInfo source, FileInfo target)
        {
            try
            {
                var buffer = new byte[BufferSize];

                // open the files before the copy
                FileStream
                    ins0 = source.OpenRead();
                target.Delete();
                FileStream xout = target.OpenWrite();

                // perform the copy
                int packetSize = 0;

                while (packetSize != -1)
                {
                    packetSize = ins0.Read(buffer, 0, buffer.Length);
                    if (packetSize != -1)
                    {
                        xout.Write(buffer, 0, packetSize);
                    }
                }

                // close the files after the copy
                ins0.Close();
                xout.Close();
            }
            catch (IOException e)
            {
                throw new EncogError(e);
            }
        }
        /// <summary>
        /// Tests preprocessing data from a PBF file.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pbfFile"></param>
        public static void TestSerialization(string name, string pbfFile)
        {
            FileInfo testFile = new FileInfo(string.Format(@".\TestFiles\{0}", pbfFile));
            Stream stream = testFile.OpenRead();
            PBFOsmStreamSource source = new PBFOsmStreamSource(stream);

            FileInfo testOutputFile = new FileInfo(@"test.routing");
            testOutputFile.Delete();
            Stream writeStream = testOutputFile.OpenWrite();

            CHEdgeGraphFileStreamTarget target = new CHEdgeGraphFileStreamTarget(writeStream,
                Vehicle.Car);
            target.RegisterSource(source);

            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("CHSerializer");
            performanceInfo.Start();
            performanceInfo.Report("Pulling from {0}...", testFile.Name);

            var data = CHEdgeGraphOsmStreamTarget.Preprocess(
                source, new OsmRoutingInterpreter(), Vehicle.Car);

            TagsCollectionBase metaData = new TagsCollection();
            metaData.Add("some_key", "some_value");
            var routingSerializer = new CHEdgeDataDataSourceSerializer(true);
            routingSerializer.Serialize(writeStream, data, metaData);

            stream.Dispose();
            writeStream.Dispose();

            OsmSharp.Logging.Log.TraceEvent("CHSerializer", OsmSharp.Logging.TraceEventType.Information,
                string.Format("Serialized file: {0}KB", testOutputFile.Length / 1024));

            performanceInfo.Stop();
        }
Ejemplo n.º 48
0
    protected void gdvFiles_Info_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        OA.OAService service = new OA.OAService();
        OA.BoardModel model = new OA.BoardModel();
        model.BOARD_ID =int.Parse(gdvFiles.DataKeys[e.RowIndex].Value.ToString());

        DataSet ds = service.BBS_Board_Delete(model, strAccount);
        if (ds != null && ds.Tables.Count > 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string[] removes = dr["ATTACHMENT_ID"].ToString().Split('*');
                foreach (string strremove in removes)
                {
                    if (strremove != "")
                    {
                        System.IO.FileInfo info = new System.IO.FileInfo(Request.PhysicalApplicationPath + "\\Attachment\\BBS\\" + strremove);
                        info.Delete();
                    }
                }
            }
            Response.Write("<script>alert('删除成功!');</script>");
            DataBound();
        }
        else
            Response.Write("<script>alert('删除失败,请与管理员联系!');</script>");
    }
        public Task<bool> Create(string namePath, byte[] inputBytes)
        {
            bool completed = false;

            try
            {
                FileInfo file = new FileInfo(namePath);
                if (file.Exists)
                {
                    file.Delete();
                }

                using (Stream fileStream = File.Create(namePath))
                {
                    fileStream.Write(inputBytes, 0, inputBytes.Length);
                }

                completed = true;
            }
            catch
            {
                completed = false;
            }

            return Task.FromResult(completed);
        }
Ejemplo n.º 50
0
        /// <summary>
        /// Creates a file from a list of strings; each string is placed on a line in the file.
        /// </summary>
        /// <param name="TempFileName">Name of response file</param>
        /// <param name="Lines">List of lines to write to the response file</param>
        public static string Create(string TempFileName, List<string> Lines)
        {
            FileInfo TempFileInfo = new FileInfo( TempFileName );
            DirectoryInfo TempFolderInfo = new DirectoryInfo( TempFileInfo.DirectoryName );

            // Delete the existing file if it exists
            if( TempFileInfo.Exists )
            {
                TempFileInfo.IsReadOnly = false;
                TempFileInfo.Delete();
                TempFileInfo.Refresh();
            }

            // Create the folder if it doesn't exist
            if( !TempFolderInfo.Exists )
            {
                // Create the
                TempFolderInfo.Create();
                TempFolderInfo.Refresh();
            }

            using( FileStream Writer = TempFileInfo.OpenWrite() )
            {
                using( StreamWriter TextWriter = new StreamWriter( Writer ) )
                {
                    Lines.ForEach( x => TextWriter.WriteLine( x ) );
                }
            }

            return TempFileName;
        }
Ejemplo n.º 51
0
        public static void LogError(Exception ex)
        {
            try
            {
                FileInfo ErrorLog = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\Decal Plugins\" + Globals.PluginName + @"\" + Globals.PluginName + "errors.txt");
                if(ErrorLog.Exists)
                {
                    if(ErrorLog.Length > 1000000) {ErrorLog.Delete();}
                }

                using (StreamWriter writer = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\Decal Plugins\" + Globals.PluginName + @"\" + Globals.PluginName + "errors.txt", true))
                {
                    writer.WriteLine("============================================================================");
                    writer.WriteLine(DateTime.Now.ToString());
                    writer.WriteLine("Error: " + ex.Message);
                    writer.WriteLine("Source: " + ex.Source);
                    writer.WriteLine("Stack: " + ex.StackTrace);
                    if (ex.InnerException != null)
                    {
                        writer.WriteLine("Inner: " + ex.InnerException.Message);
                        writer.WriteLine("Inner Stack: " + ex.InnerException.StackTrace);
                    }
                    writer.WriteLine("============================================================================");
                    writer.WriteLine("");
                    writer.Close();
                }
            }
            catch
            {
            }
        }
Ejemplo n.º 52
0
        public void RemoveTempFiles()
        {
            schemaFile.Dispose();

            FileInfo info = new FileInfo(tempFile);
            if(info.Exists) info.Delete();
        }
        /// <summary>
        /// Called when the delete button is clicked
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void BtnDeleteClick(object sender, EventArgs e)
        {
            if(this.lstImages.SelectedItem  == null)
                return;

            string filename = this.lstImages.SelectedItem.ToString();
            FileInfo info = new FileInfo("images\\" + filename);

            if(info.Exists)
            {
                if(MessageBox.Show("Delete " + filename + "?","Confirm",MessageBoxButtons.OKCancel,MessageBoxIcon.Exclamation) == DialogResult.OK)
                {
                    try
                    {
                        this.pictureBox1.Image.Dispose();
                        info.Delete();
                    }
                    catch(Exception excep)
                    {
                        MessageBox.Show("Could not delete file: \n\t" + excep.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    }
                }
                else
                    return;

            }

            this.Refresh();
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Migrates the specified file name and path.
        /// <remarks>This method is called directly when performing integration tests.</remarks>
        /// </summary>
        /// <param name="fileNameAndPath">The file name and path.</param>
        /// <param name="withBackup">if set to <c>true</c> [with backup].</param>
        /// <param name="withAnnouncer">if set to <c>true</c> [with announcer].</param>
        public static void Migrate(string fileNameAndPath, bool withBackup = false, bool withAnnouncer = false)
        {
            var currentDb = new FileInfo(fileNameAndPath);
            var backupDb = string.Empty;

            if (withBackup) { Backup(currentDb); }

            var emptyAnnouncers = new Announcer[] { };
            var consoleAnnouncer = new Announcer[] { new ConsoleAnnouncer() };
            var announcerToProvide = new CompositeAnnouncer(withAnnouncer ? consoleAnnouncer : emptyAnnouncers);

            var ctx = new RunnerContext(announcerToProvide)
            {
                ApplicationContext = string.Empty,
                Database = "sqlite",
                Connection = string.Format(CONNECTION_STRING_FORMAT, fileNameAndPath).NormalizePathSeparator(),
                Targets = new[] { "Drey.Configuration" }
            };

            try
            {
                var executor = new TaskExecutor(ctx);
                executor.Execute();
            }
            catch (Exception)
            {
                if (withBackup)
                {
                    currentDb.Delete();
                    if (!string.IsNullOrWhiteSpace(backupDb)) { File.Copy(backupDb, currentDb.FullName); }
                }

                throw;
            }
        }
Ejemplo n.º 55
0
        public void DeleteTime()
        {
            using (StreamWriter fs = new StreamWriter(file2.ToString(), false, System.Text.Encoding.Default))
            {
                string pl = DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year.ToString() + " " + DateTime.Now.Hour.ToString() + ":";

                string str = "";
                Console.WriteLine(pl);
                using (StreamReader reader = new StreamReader(file.ToString(), System.Text.Encoding.Default))
                {
                    while (true)
                    {
                        if (reader.EndOfStream)
                        {
                            break;
                        }
                        srt = reader.ReadLine();
                        if (str.Contains(pl))
                        {
                            fs.WriteLine(str);
                        }
                    }
                }
            }
            file.Delete();
            file2.MoveTo("C://for13lab//LOGfile.txt");
        }
        public void TestStorage()
        {
            var temp = new FileInfo(Path.GetTempFileName());
            try
            {
                Console.WriteLine(temp.FullName);
                var @params = NetworkParameters.UnitTests();
                var to = new EcKey().ToAddress(@params);
                StoredBlock b1;
                using (var store = new BoundedOverheadBlockStore(@params, temp))
                {
                    // Check the first block in a new store is the genesis block.
                    var genesis = store.GetChainHead();
                    Assert.AreEqual(@params.GenesisBlock, genesis.Header);

                    // Build a new block.
                    b1 = genesis.Build(genesis.Header.CreateNextBlock(to).CloneAsHeader());
                    store.Put(b1);
                    store.SetChainHead(b1);
                }
                // Check we can get it back out again if we rebuild the store object.
                using (var store = new BoundedOverheadBlockStore(@params, temp))
                {
                    var b2 = store.Get(b1.Header.Hash);
                    Assert.AreEqual(b1, b2);
                    // Check the chain head was stored correctly also.
                    Assert.AreEqual(b1, store.GetChainHead());
                }
            }
            finally
            {
                temp.Delete();
            }
        }
Ejemplo n.º 57
0
 protected void lbImgUpload_Click(object sender, EventArgs e)
 {
     if (txtBookName.Text != "" && imgUpload.HasFile)
     {
         string filepath = imgUpload.PostedFile.FileName;
         string pat      = @"\\(?:.+)\\(.+)\.(.+)";
         Regex  r        = new Regex(pat);
         Match  m        = r.Match(filepath);
         //string file_ext = m.Groups[2].Captures[0].ToString();
         //string filename = m.Groups[1].Captures[0].ToString();
         string             file_ext = "jpg";
         string             file     = txtBookName.Text + "." + file_ext;
         System.IO.FileInfo files    = new System.IO.FileInfo(MapPath(file));
         if (files.Exists)
         {
             files.Delete();
         }
         int width  = 145;
         int height = 165;
         using (System.Drawing.Bitmap img = DataManager.ResizeImage(new System.Drawing.Bitmap(imgUpload.PostedFile.InputStream), width, height, DataManager.ResizeOptions.ExactWidthAndHeight))
         {
             img.Save(Server.MapPath("img/") + file);
             imgUpload.PostedFile.InputStream.Close();
             ImageLogo = DataManager.ConvertImageToByteArray(img, System.Drawing.Imaging.ImageFormat.Tiff);
             img.Dispose();
         }
         string strFilename = "img/" + file;
         imgLogo.ImageUrl = "~/tmpHandler.ashx?filename=" + strFilename + "";
     }
     else
     {
         ClientScript.RegisterStartupScript(this.GetType(), "ale", "alert('Please input book name, and then browse an image!!');", true);
     }
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Removes file specified by destination
        /// </summary>
        /// <param name="destination">Absolute path of the file to be removed.</param>
        private void RemoveFileThrowIfError(string destination)
        {
            Diagnostics.Assert(System.IO.Path.IsPathRooted(destination),
                               "RemoveFile expects an absolute path");

            System.IO.FileInfo destfile = new System.IO.FileInfo(destination);
            if (destfile != null)
            {
                Exception e = null;
                try
                {
                    //Make sure the file is not read only
                    destfile.Attributes = destfile.Attributes & ~(FileAttributes.ReadOnly | FileAttributes.Hidden);
                    destfile.Delete();
                }
                catch (FileNotFoundException fnf)
                {
                    e = fnf;
                }
                catch (DirectoryNotFoundException dnf)
                {
                    e = dnf;
                }
                catch (UnauthorizedAccessException uac)
                {
                    e = uac;
                }
                catch (System.Security.SecurityException se)
                {
                    e = se;
                }
                catch (ArgumentNullException ane)
                {
                    e = ane;
                }
                catch (ArgumentException ae)
                {
                    e = ae;
                }
                catch (PathTooLongException pe)
                {
                    e = pe;
                }
                catch (NotSupportedException ns)
                {
                    e = ns;
                }
                catch (IOException ioe)
                {
                    e = ioe;
                }

                if (e != null)
                {
                    throw PSTraceSource.NewInvalidOperationException(e,
                                                                     ConsoleInfoErrorStrings.ExportConsoleCannotDeleteFile,
                                                                     destfile);
                }
            }
        }
Ejemplo n.º 59
0
        public void unpackTag(string tagUrl, string unpackDirectory)
        {
            bool firstDir = true;
            string firstDirPath = "";

            var tagFile = getTagFilePath(tagUrl, unpackDirectory);

            using (ZipFile tag = ZipFile.Read(tagFile))
            {
                foreach (ZipEntry entry in tag)
                {
                    if (firstDir)
                    {
                        firstDirPath = entry.FileName;
                        firstDir = false;
                    }
                    entry.Extract(unpackDirectory, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            DirectoryCopy(unpackDirectory + "\\" + firstDirPath, unpackDirectory);

            FileInfo f = new FileInfo(tagFile);
            f.Delete();
        }
Ejemplo n.º 60
-1
        /// <summary>
        /// Descomprime el archivo especificado en el directorio correspondiente
        /// </summary>
        /// <param name="fi"></param>
        public static string decompressFile(FileInfo fi)
        {
            string name = fi.Name.ToString().Replace(".pkg", "");

            FileInfo zipfile = fi.CopyTo(name + ".zip" ,true);
            string dirDestino = fi.Directory.FullName + @"\" + name;
            if(Directory.Exists(dirDestino)==true)
            {
                Directory.Delete(dirDestino,true);

            }
            Directory.CreateDirectory(dirDestino);

            fi.Delete();
            Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile(zipfile.FullName);
            zf.ExtractAll(dirDestino,Ionic.Zip.ExtractExistingFileAction.OverwriteSilently);
            Console.WriteLine("extraido aunque no lo parezca");
            return dirDestino;
            /*
            using (FileStream infile = fi.OpenRead())
            {
                string curfile = fi.FullName;
                string originalName = curfile.Remove(curfile.Length - fi.Extension.Length);

                using (FileStream outfile = File.Create(originalName))
                {

                    using (GZipStream decompress = new GZipStream(infile, CompressionMode.Decompress))
                    {
                        decompress.CopyTo(outfile);
                    }
                }
            }
                 */
        }