public void OnSaveButtonClick() { FileOpCanvas.SetActive(false); string path = "Molecule" + DateTime.Now.ToString(); FileOperator.SaveModel(path); }
private void saveTriangleIndexToFile(string fileName) { float[] shoulderL = planes.getControlPlane("shoulderLeft"); float[] shoulderR = planes.getControlPlane("shoulderRight"); //float[] back = planes.getControlPlane ("back"); int[] tri = clothMesh.triangles; //Vector3[] vertices = clothMesh.vertices; Vector3[] vertices = clothVertices; string data = ""; int index = 0; for (int i = 0; i < tri.Length; i += 3, index++) { for (int j = 0; j < 3; j++) { if (!AuxMath.isAbovePlane(vertices [tri [i + j]], shoulderL) && !AuxMath.isAbovePlane(vertices [tri [i + j]], shoulderR) ) { data += index.ToString() + " "; break; } } } FileOperator.SaveDataToFile(fileName, data); }
/// <summary> /// 名称リストのファイルを読込む。 /// </summary> /// <param name="filePath">読込対象となるファイル</param> /// <returns>true:読込成功、false:それ以外</returns> /// <remarks>読込に成功した場合は情報を`DataContext`に設定する。 /// 最初に`DataContext`をクリアするので読込失敗時は`DataContext`が空になる。</remarks> internal bool FileLoad(string filePath) { this.DataContext.Clear(); using (var file = new FileOperator(filePath)) { if (!file.Exists()) { return(false); } file.OpenForRead(); while (!file.Eof) { var item = file.ReadLine().Split(Separator); Array.Resize(ref item, 3); this.DataContext.Add(new NameModel() { EnglishName = item[0], JapaneseName = item[1], Note = item[2] }); } this.FileName = file.Name; } this.FilePath = filePath; this._currentSortType = SortType.EnAsc; this.SortBySortType(); return(true); }
void updateFromFile() { if (humanData == null) { humanData = FileOperator.LoadDataFromFile("/Samples/train.txt", out humanDataGap); } if (humanDataIndex + humanDataGap <= humanData.Length) { height = humanData [humanDataIndex]; crotchHeight = humanData [humanDataIndex + 1]; kneeHeight = humanData [humanDataIndex + 2]; forearmLength = humanData [humanDataIndex + 4]; armLength = humanData [humanDataIndex + 3]; shoulderWidth = humanData [humanDataIndex + 5]; bustGrith = humanData [humanDataIndex + 6]; waistGrith = humanData [humanDataIndex + 7]; hipGrith = humanData [humanDataIndex + 8]; thighGrith = humanData [humanDataIndex + 9]; calfGrith = humanData [humanDataIndex + 10]; humanDataIndex += humanDataGap; bool isHeightChanged = (Mathf.Abs(height - preHeight) < 1e-3) ? false : true; if (!isHeightChanged) { //MessageManager.SendMessage (GlobalSignal.GlobalMsg1); MessageManager.SendMessage(GlobalSignal.GlobalMsg2); } else { MessageManager.SendMessage(GlobalSignal.GlobalMsg2); } } }
public void Analyze(bool replace) { if (!FileOperator.CheckExitsFile(_baseFile)) { return; } if (!FileOperator.CheckNotZeroLength(_baseFile)) { return; } string tempFullPath = null; if (replace) //If search substring and replace it with the pattern { bool tempFileCreated = FileOperator.TempFileCreateOrDelete(_baseFile, TEMP_FILE_NAME, out tempFullPath); if (!string.IsNullOrEmpty(tempFullPath)) { ParserText.ReplacePatternInFile(_baseFile, tempFullPath, _searchString, _pattern, tempFileCreated); FileOperator.ReplaceFiles(_baseFile, tempFullPath); } } else //Count sunbstrings inclusions amount { bool resultFileCreated = FileOperator.TempFileCreateOrDelete(_baseFile, RESULT_FILE_NAME, out tempFullPath); if (!string.IsNullOrEmpty(tempFullPath)) { ParserText.CountContainedInFile(_baseFile, RESULT_FILE_NAME, _searchString, resultFileCreated); } } }
/// <summary> /// 构造函数,创建一个指定文件路径的IO操作安全文件操作实例,并根据参数createdThenNotExists决定当文件不存在时是否创建新文件。 /// </summary> /// <param name="fileUrl">用于被操作的IO操作安全文件的文件地址,如果这个文件不存在,会重新创建一个新的文件地址为当前参数的文件。</param> /// <param name="createdThenNotExists">用于决定是否在检测到文件不存在时来创建新文件。</param> /// <exception cref="FileNotFoundException">当参数fileUrl指定的文件找不到,并且不允许根据参数createdThenNotExists决定当文件不存在时是否创建新文件的情况下,则会抛出这个异常。</exception> public IOSecurityFile(string fileUrl, bool createdThenNotExists) { if (createdThenNotExists) { if (!FileOperator.FileExists(fileUrl)) { ExString ciphertext = ExString.Encrypt(string.Empty, FILE_SECURITY_KEY); FileOperator.CreateFile(fileUrl); FileOperator.WriteFile(fileUrl, ciphertext, false); } } else { if (!FileOperator.FileExists(fileUrl)) { throw new FileNotFoundException("指定的文件找不到!", fileUrl); } } ChangeCodeSecurityFlag(CODE_SECURITY_FLAG_STOP); CloseWritePassageway(); _securityFileUrl = fileUrl; _fileContext = string.Empty; _isApplyAccessRule = true; SetPrimeMD5Code(); }
/// <summary> /// 读取匹配结果 /// 文件结构 /// 数据类型 /// 结果 /// </summary> /// <param name="isLoopDebug"></param> /// <returns></returns> public ResultInfo ReadFromFile(bool isLoopDebug) { ResultInfo result = new ResultInfo(); try { string content = FileOperator.ReadFromFile2(_Path); if (content != null) { string[] resMatch = content.Split('\n'); if (resMatch.Length >= 2) { result.DataType = resMatch[0]; result.Result = resMatch[1]; } // this.picWin.setMatch(curPercent); // this.picWin.ShowCounter(); } } catch { } finally { if (isLoopDebug) { File.Delete(_Path); } } return(result); }
public async Task Copy(Dir _path) { if (CurrentDirInfo.Exists && _path.Exists()) //&& !_path.Info.FullName.Contains(this.Info.FullName) && !_path.IsExistsHere(this.Info.ShortName)) { try { Dir tempdir = FileOperator.MkDirFile(Path.Combine(_path.Info.FullName, this.Info.ShortName), true) as Dir; foreach (File fobj in this.GetFiles()) { await Task.Run(() => fobj.Copy(tempdir)); } foreach (Dir dobj in this.GetDirectories()) { await Task.Run(() => dobj.Copy(tempdir)); } } catch (Exception ex) { throw new Exception($"Copy directory is unavailable: {ex.Message}"); } } else { throw new Exception($"Can't copy in directory {_path.Info.ShortName}"); } }
private string GetEditorTemplate() { string templatePath = AssetDatabase.GetAssetPath(MonoScript.FromScriptableObject(this)); templatePath = templatePath.Replace(this.GetType().ToString().Replace(this.GetType().Namespace + ".", "") + ".cs", "NodeEditorTemplate.ntp"); return(FileOperator.LoadStringFromFile(FileOperator.GetProjectPath() + templatePath)); }
public void doService() { //the ODM crash files will move to ODM dir from LUT moveODMFiles(configData.LUTPath, configData.ODM_PATH); configData.currentDate = FileOperator.geStringtDate(); FileOperator.createDateFolder(configData.currentDate); clearContains(); //get all crash report files getCrashFiles(ref crashFileList); Trace.WriteLine("********* The Total number of Crash Reports is : " + crashFileList.Count + " *********"); //from the name of crash file, get the delivry time and imei foreach (CrashFileTypeInfo fileTypeInfo in crashFileList) { CrashFileNameInfo nameInfo = logFactory.buildFileNameInfo(fileTypeInfo); fileNameInfoList.Add(nameInfo); } Trace.WriteLine("********* The valid Crash Reports is : " + fileNameInfoList.Count + " *********"); //do mathing with delivery time and imei processManager.matchCrashFile(fileNameInfoList, ref logInfoList); Trace.WriteLine("********* After do matching, there have " + logInfoList.Count + " crash reports *********"); //move crash reports to result directory and record the match result into DB. resultManager.handleMatchResults(logInfoList); }
public void getCrashFiles(ref List <CrashFileTypeInfo> fileList) { FileOperator.getCrashFile(configData.PCCPath, ref fileList, EFrom.CMM); FileOperator.getCrashFile(configData.LUTPath, ref fileList, EFrom.LUT); FileOperator.getCrashFile(configData.EXTPath1, ref fileList, EFrom.EXT1); FileOperator.getCrashFile(configData.EXTPath2, ref fileList, EFrom.EXT2); }
public async Task <FileStreamResult> ExportToPdf(string htmlContent, bool rotate) { var pageSize = rotate ? PageSize.A4.Rotate() : PageSize.A4; var convertRequest = new ConvertRequest { Content = htmlContent, Footer = PdfFormation.PageNumberFooterTemplate }; var pdfConverter = new PdfHtmConverter(convertRequest); var memoryStream = pdfConverter.ManipulatePdf(pageSize); var guid = Guid.NewGuid(); var outputFilePath = $"report_{guid}.pdf"; var finalOutputFilePath = $"final_report_{guid}.pdf"; await PdfFileWriter.SaveToFile(memoryStream, outputFilePath); _logger.LogInformation($"Saved pdf file {outputFilePath}"); pdfConverter.DecoratePdf(outputFilePath, finalOutputFilePath); var response = PdfFileReader.ReadFrom(finalOutputFilePath); FileOperator.Delete(outputFilePath); _logger.LogInformation($"Deleted pdf file {outputFilePath}"); FileOperator.Delete(finalOutputFilePath); _logger.LogInformation($"Deleted pdf file {finalOutputFilePath}"); return(new FileStreamResult(response, "application/pdf")); }
// 导入数据事件 private void btnImport_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter = "TXT文件(*.txt)|*.txt|CSV文件(*.csv)|*.csv|所有文件(*.*)|*.*"; if (openFile.ShowDialog() == DialogResult.OK) { fileName = openFile.FileName; } try { FileOperator fileOperator = new FileOperator(); employeeList = fileOperator.ReadFile(fileName); // 读取文件并赋值给list } catch (Exception exp) { MessageBox.Show("导入错误:" + exp.Message, "出错啦!", MessageBoxButtons.OK, MessageBoxIcon.Information); } // 将dataGridView数据源绑定为List 并禁止生成新的列 dgvEmployeeShow.DataSource = null; dgvEmployeeShow.AutoGenerateColumns = false; dgvEmployeeShow.DataSource = employeeList; // 将表格中第一行数据默认显示到编辑区 Employee employee = employeeService.GetEmployeeById(dgvEmployeeShow.Rows[0].Cells[0].Value.ToString(), employeeList); LoadDataDetail(employee); // 清除没有导入数据时查询的文本框内容 tbQueryId.Text = ""; tbQueryName.Text = ""; }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Create_Click(object sender, RoutedEventArgs e) { var data = new StringBuilder(); var converter = new RomanTableConverter(); string parent; using (var src = new FileOperator(this.cFile.Text)) { if (!src.Exists()) { MessageBox.Show("invalid input file"); return; } parent = src.FileDir; src.OpenForRead(); while (!src.Eof) { data.AppendLine(converter.Convert(src.ReadLine())); } } using (var dest = new FileOperator(parent + @"\mapping.html")) { var template = new FileOperator(OsnCsLib.Common.Util.GetAppPath() + @"Res\index.html").ReadAll(); dest.Delete(); dest.OpenForWrite(); dest.Write(template.Replace("<!--container-->", data.ToString())); } var settings = AppRepository.GetInstance(); settings.ConvertFile = this.cFile.Text; settings.Save(); }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { string secondDirPath = null; try { var dir = new DirectoryInfo(folderBrowserDialog2.SelectedPath); secondDirPath = dir.FullName; } catch (Exception) { Console.WriteLine($"Error: folderBrowserDialog2 don`t entered"); } var userOptions = new UserOptions(GetFolding(), GetTitle(), moveToFolderCheckBox.Checked, secondDirPath); var mp3Files = new DirectoryInfo(folderBrowserDialog1.SelectedPath) .GetFiles("*.mp3", SearchOption.AllDirectories); var fileOperator = new FileOperator(userOptions); for (int i = 0; i < mp3Files.Length; i++) { fileOperator.SetTarget(mp3Files[i]); fileOperator.DoStuff(); int percentage = (i + 1) * 100 / mp3Files.Length; backgroundWorker1.ReportProgress(percentage); } }
/// <summary> /// initialize app /// </summary> private void Initialize() { // initialize var settings = AppRepository.Init(Constants.SettingFile); this.cNormalKeyMapping.DataContext = new KeyMappingViewModel(); this.cFnKeyMapping.DataContext = new KeyMappingViewModel(); // read mapping information using (var reader = new FileOperator(Constants.KeyMappingFIle, FileOperator.OpenMode.Read)) { while (!reader.Eof) { var pair = reader.ReadLine().Split('\t'); if (this._keyMapping.ContainsKey(int.Parse(pair[0]))) { ErrorMessage.Show(ErrMsgId.MappingKeyIsDuplicated); break; } else { this._keyMapping.Add(int.Parse(pair[0]), pair[1].Replace("@r@", "\r\n")); } } } // set dip siwtch text color this._onBg = this.GetColorFromRgb("#7373FF"); this._offBg = this.GetColorFromRgb("#DDDDDD"); // restore if possible this.ShowKeyMapping(settings.HskFile); }
//读取图片坐标信息,生成featureArea.h public string AnalyseFeatherHeaderFile(string savePath, string inputFilePath) { try { if (!File.Exists(savePath + FeatherName)) { // CassMessageBox.Information("当前工程不存在" + FeatherName + "文件!"); return("当前工程不存在" + FeatherName + "文件!"); } //读取feather.h文件 string fileContent = FileOperator.ReadFromFile2(savePath + FeatherName); string writeContent = null; if (fileContent == null)//当feather.h文件为空时,默认读取全图尺寸 { writeContent = GenerateDefaltFeatureAreaFile(inputFilePath); CassMessageBox.Information("当前为默认状态,全图操作。"); } else { writeContent = AnalyseFeatherContent(fileContent); } FileOperator.WriteToFile(savePath + FeatureAreaName, writeContent, Encoding.UTF8); } catch (Exception ex) { return(ex.ToString()); } return(null); }
// Console Renderer's constructor public ConsoleRenderer(GameFieldCoords size) { this.InitializeGameField(size); this.gameFieldSize = size; this.consoleSize = new GameFieldCoords(this.gameFieldSize.Row + 2, this.gameFieldSize.Col + 21); this.highScores = FileOperator.ReadHighScoreFile(); Console.CursorVisible = false; Console.WindowHeight = this.consoleSize.Row; Console.BufferHeight = Console.WindowHeight; Console.WindowWidth = this.consoleSize.Col; Console.BufferWidth = Console.WindowWidth; this.InitializeCursorPostions(); }
/// <summary> /// 通过指定的应用程序名称从启动目录中删除一个自启动项目。 /// </summary> /// <param name="assemblyName">指定的应用程序名称或者是启动目录中这个自启动项目的快捷方式名称。</param> public static void DeleteStartupWithBootMenu(string assemblyName) { string bootMenuPath = Environment.GetFolderPath(Environment.SpecialFolder.Startup); string willDeletedInkFile = bootMenuPath + "\\" + assemblyName + ".lnk"; FileOperator.DeleteFile(willDeletedInkFile); }
public static void linkToBackup(string file) { Directory.CreateDirectory(Path.Combine(BackupDir, StringOperator.GetRootChar(file), StringOperator.GetDirectoryNameExceptRoot(file))); FileOperator.MkLinkOption option; bool isFile; if (File.Exists(file)) { option = FileOperator.MkLinkOption.HardLink; isFile = true; } else if (Directory.Exists(file)) { option = FileOperator.MkLinkOption.Junction; isFile = false; } else { Console.WriteLine("ファーwww"); throw new FileNotFoundException(); } string linkDirectory = Path.Combine(BackupDir, StringOperator.GetRootChar(file), StringOperator.GetFileNameExceptRoot(file)); string originalDirectory = file; bool noerror = FileOperator.MkLink(linkDirectory, originalDirectory, option).CheckNoError(); //いちいちトランザクション生成して遅いらしいけど、暫定。 if (noerror) { (new SQLDataBase("sync.db")).InsertToDB(new SQLDataBase.FilesTable(isFile, linkDirectory, originalDirectory)); } }
static void Main(string[] args) { string _SQLConnectionString = "Data Source=MAKSIMOV;Initial Catalog=GBUMATC;Integrated Security=False;User ID=Бушмакин;Password=453459;"; log4net.Config.XmlConfigurator.Configure(); DirectoryInfo di; List <DirectoryInfo> dList = new List <DirectoryInfo>(); List <FileInfo> h; DirectoryInfo _directory = new DirectoryInfo("e:\\111"); DirectoryInfo[] directories;//= _directory.GetDirectories(); List <FileInfo> OldFiles = new List <FileInfo>(); foreach (string dir in args) { di = new DirectoryInfo(dir); dList.Add(di); h = new List <FileInfo>(); } FileOperator FOp = new FileOperator(new SqlConnection(_SQLConnectionString), LogManager.GetLogger(typeof(FileOperator)), false); OldFiles = new List <FileInfo>(); directories = new DirectoryInfo[] { _directory }; matcFileName mmm = new matcFileName("01111ГУ987654_20180202", "^(\\d{5}ГУ\\d{6})(?:_(.*))*_(\\d{8})(?:_(\\d{1,2}))*$"); var yyy = FOp.lsToFileInfoW(_directory, "^(\\d{5}ГУ\\d{6})(?:_(.*))*_(\\d{8})(?:_(\\d{1,2}))*$").ToList(); var yyy1 = FOp.CalcNumber(yyy.Where(sel => sel.Name.Number == null).ToList()); List <List <FileInfoW> > ll = new List <List <FileInfoW> >(); FOp.TransferableFilesList = yyy; Task t2 = Task.Factory.StartNew(() => { FOp.MD5CalculateParallel(FOp.TransferableFilesList, 7); }); t2.Wait(); ll.Add(yyy); FOp.selectDubbles(ll); foreach (var y in yyy1) { y.NeedRename = true; } FOp.DestinationDirectory = new DirectoryInfo("Z:\\"); FOp.calculateTransferableFilesList(); FOp.LoadDestinationByNumbers(); FOp.CreateTasks().Last().Wait(); /*Task t1 = Task.Factory.StartNew(() => * { FOp.MD5CalculateParallel(FOp.DestinationFilesList, 7); }); * //t1.Start(); * * t1.Wait();*/ var rt = FOp.DestinationFilesList; FOp.Load(dList); }
private void ShowFileInfo() { FileOperator fileOperator = new FileOperator(); string filePath = fileOperator.GetPathByOpen(null); FileData fileInfo = fileOperator.GetFileInfo(filePath); MessageBox.Show(fileInfo.GetFileInfo()); }
/// <summary> /// 构造函数,创建一个指定快捷方式名称和指向源地址的快捷方式生成实例。 /// </summary> /// <param name="name">指定的快捷方式名称。</param> /// <param name="webOrFileUrl">快捷方式所对应的源文件或者Web地址。</param> public ShortcutCreator(string name, string webOrFileUrl) { _name = name; _webOrFileUrl = new Uri(webOrFileUrl); _localDirectory = FileOperator.GetFatherDirectory(webOrFileUrl); _icon = null; _description = webOrFileUrl; }
/// <summary> /// 构造函数,通过一个指定的数据库文件地址和数据库访问密码来初始化当前实例。 /// </summary> /// <param name="dbFileUrl">指定的数据库文件地址,如果这个文件地址无效则会抛出FileNotFoundException异常。</param> /// <param name="dbPassword">指定的数据库访问密码。</param> /// <exception cref="FileNotFoundException">如果找不到dbFileUrl参数指定的数据库文件,则会抛出这个异常。</exception> public SQLiteDBOIEncapsulation(string dbFileUrl, string dbPassword) { if (FileOperator.FileExists(dbFileUrl) == false) { throw new FileNotFoundException("找不到数据库文件!"); } _dbConnectionString = "Data Source=" + dbFileUrl + "; Password" + dbPassword + ";"; }
private string _appSettingFileUrl;//应用程序配置文件路径。 /// <summary> /// 构造函数,创建一个指定应用程序配置文件的应用程序配置实例。 /// </summary> /// <param name="appSettingFileUrl">指定的应用程序配置文件地址,如果这个文件地址不存在,那么会自动创建一个空的配置文件。</param> public AppSettings(string appSettingFileUrl) { if (!FileOperator.FileExists(appSettingFileUrl)) { FileOperator.CreateFile(appSettingFileUrl); } _appSettingFileUrl = appSettingFileUrl; }
/// <summary> /// 创建一个进程,在创建这个进程的时候会指定相关的权限和域。 /// </summary> /// <param name="executeFileUrl">需要创建进程的一个Windows可执行文件。</param> /// <param name="userName">启动进程时使用的用户名。</param> /// <param name="password">一个SecureString实例,它包含启动进程时要使用的密码。</param> /// <param name="domian">启动进程时要使用的域。</param> /// <returns>该方法会返回这个进程的System.Diagnostics.Process实例。</returns> /// <exception cref="FileNotFoundException">当指定的Windows可执行文件找不到时,则会抛出这个异常。</exception> public static Process CreateProcess(string executeFileUrl, string userName, SecureString password, string domian) { if (!FileOperator.FileExists(executeFileUrl)) { throw new FileNotFoundException("指定的Windows可执行文件不存在!"); } return(Process.Start(executeFileUrl, userName, password, domian)); }
private SQLiteConnection _sqlConnection; //SQLite数据库连接类。 /// <summary> /// 构造函数,通过一个指定的数据库文件地址来初始化当前实例。 /// </summary> /// <param name="dbFileUrl">指定的数据库文件地址,如果这个文件地址无效则会抛出FileNotFoundException异常。</param> /// <exception cref="FileNotFoundException">如果找不到dbFileUrl参数指定的数据库文件,则会抛出这个异常。</exception> public SQLiteDBOIEncapsulation(Uri dbFileUrl) : base() { if (FileOperator.FileExists(dbFileUrl.LocalPath) == false) { throw new FileNotFoundException("找不到数据库文件!"); } _dbConnectionString = "Data Source=" + dbFileUrl.LocalPath; }
/// <summary> /// 构造函数,通过一个指定的数据库文件地址和数据库访问密码来初始化当前实例,但与此同时还要指定数据库系统的版本,是否使用只读的访问模式,连接池大小,以及是否使用UTF16编码。 /// </summary> /// <param name="dbFileUrl">指定的数据库文件地址,如果这个文件地址无效则会抛出FileNotFoundException异常。</param> /// <param name="dbPassword">指定的数据库访问密码。</param> /// <param name="dbsVersion">指定的数据库系统版本,如果数据库系统版本为2.x,则这个参数可指定为2,如果数据库系统版本为3.x,则这个参数指定为3。</param> /// <param name="isUsingUTF16Encoding">决定是否使用UTF16编码。</param> /// <param name="isReadOnly">指定是否以只读的访问模式来连接这个数据库。</param> /// <param name="connectionPoolMaximumSize">指定数据库的连接池大小限制。</param> /// <exception cref="FileNotFoundException">如果找不到dbFileUrl参数指定的数据库文件,则会抛出这个异常。</exception> public SQLiteDBOIEncapsulation(string dbFileUrl, string dbPassword, int dbsVersion, bool isUsingUTF16Encoding, bool isReadOnly, int connectionPoolMaximumSize) : base() { if (FileOperator.FileExists(dbFileUrl) == false) { throw new FileNotFoundException("找不到数据库文件!"); } _dbConnectionString = "Data Source=" + dbFileUrl + "; Password" + dbPassword + "; Version=" + dbsVersion + "; UseUTF16Encoding=" + isUsingUTF16Encoding + "; Read Only=" + isReadOnly + "; Max Pool Size=" + connectionPoolMaximumSize + ";"; }
//excel表头发生变化时 private void cboExcelSheet_SelectedIndexChanged(object sender, EventArgs e) { //表头的取出 if (!string.IsNullOrEmpty(txtFilePath.Text) && cboExcelSheet.Items.Count > 0) { _currentImportStruct = FileOperator.ReadExcelHeader(this.txtFilePath.Text, CConvert.ToString(this.cboExcelSheet.SelectedValue)); DataBind(); } }
private void unZipFile(string path) { DirectoryInfo dirInfo = new DirectoryInfo(path); if (!dirInfo.Exists) { Trace.WriteLine("The directory path: " + path + " doesn't exist"); return; } FileInfo[] crashFiles = dirInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly); //only get the files created by one hour ago. List <FileInfo> tempFileList = FileOperator.deleteInvalidFile(crashFiles); Trace.WriteLine(crashFiles.Length + " , is: " + tempFileList.Count); string fullName = null; foreach (FileInfo file in tempFileList) { fullName = file.Name; Trace.WriteLine("--File Name is " + file.FullName); if (fullName.ToLower().StartsWith("crash-") && fullName.EndsWith("zip")) { if (UnzipFileHelper.unZipFile(file.FullName, configData.LUTPath + @"\" + Path.GetFileNameWithoutExtension(file.FullName))) { try { file.Delete(); } catch (Exception ex) { Trace.WriteLine("Error occured when delete: " + file.FullName + ", The details of info is: " + ex.ToString()); } } else { Trace.WriteLine("This is not success when unZip " + file.FullName); } } else { try { if (!Directory.Exists(configData.LUTPath)) { Directory.CreateDirectory(configData.LUTPath); } file.MoveTo(Path.Combine(configData.LUTPath, file.Name)); } catch (Exception ex) { Trace.WriteLine("This is not success when move the " + file.FullName + " error info: " + ex.Message); } } } }
public string EditUpload() { ProductItemMap m = new ProductItemMap(); int channel_id = int.Parse(Request.Form["channel"]); int Ins = 0; int Upd = 0; #region 讀取excel文件 string fileName = Request.Files[0].FileName; string filePath = ""; string fName = ""; string fExtension = ""; try { FileOperator fo = new FileOperator(fileName); fExtension = fo.Extension; if (fExtension != ".xls" && fExtension != ".xlsx") { return "{success:false,msg:'" + Resources.ProductItemMap.EXCEL_FORMAT_ERROR + "'}"; } if (!System.IO.Directory.Exists(Server.MapPath(excelPath))) { System.IO.Directory.CreateDirectory(Server.MapPath(excelPath)); } fName = DateTime.Now.ToString("yyyyMMddhhmmss") + fo.Extension; filePath = Server.MapPath(excelPath) + "/" + fName; } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); return "{success:false,msg:'" + Resources.ProductItemMap.EXCEL_FORMAT_ERROR + "'}"; } try { Request.Files[0].SaveAs(filePath); } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); } #endregion try { Resource.CoreMessage = new CoreResource("ProductItemMap"); //讀取excel裡賣弄的內容 NPOI4ExcelHelper fm = new NPOI4ExcelHelper(filePath); _ProductItemMapMgr = new ProductItemMapMgr(connectionString); DataTable dt = fm.SheetData(); if (dt.Rows.Count > 0) { for (int i = 0; i < dt.Rows.Count; i++) { if (_ProductItemMapMgr.Selrepeat(dt.Rows[i]["外站商品編號"].ToString()) > 0) {//編輯 try { m.channel_detail_id = dt.Rows[i]["外站商品編號"].ToString(); m.product_name = dt.Rows[i]["外站商品名稱"].ToString(); m.product_price = Int32.Parse(dt.Rows[i]["外站商品售價"].ToString()); _ProductItemMapMgr.UpdatePIM(m); Upd++; } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); } } else {//保存 未知price_master_id try { m.channel_id = UInt32.Parse(channel_id.ToString()); m.channel_detail_id = dt.Rows[i]["外站商品編號"].ToString(); m.product_name = dt.Rows[i]["外站商品名稱"].ToString(); try { m.product_id = UInt32.Parse(dt.Rows[i]["商品編號(5碼)"].ToString()); } catch { m.product_id = 0; } try { m.item_id = UInt32.Parse(dt.Rows[i]["商品細項編號(6碼)"].ToString()); } catch { m.item_id = 0; } //m.product_cost = Int32.Parse(dt.Rows[i]["外站商品成本"].ToString()); try { m.product_price = Int32.Parse(dt.Rows[i]["外站商品售價"].ToString()); } catch { m.product_price = 0; } _ProductItemMapMgr.Save(m); Ins++; } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); } } } return "{success:true,msg:'新增成功" + Ins + "條,更新成功" + Upd + "條'}"; } else return "{success:false,msg:'Excel no data'}"; } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); return "{success:false,msg:'" + Resources.ProductItemMap.IMPORT_FAIL + "'}"; } //return "{success:true,msg:'" + string.Format(Resources.ProductItemMap.IMPORT_SUCCESS_TOTAL, Ins+Upd) + "'}"; }
public string DoUpload() { int channel_id = int.Parse(Request.Form["w_comboxOutSite"]); string fileName = Request.Files[0].FileName; string filePath = ""; string fName = ""; string fExtension = ""; try { FileOperator fo = new FileOperator(fileName); fExtension = fo.Extension; if (fExtension != ".xls" && fExtension != ".xlsx") { return "{success:false,msg:'" + Resources.ProductItemMap.EXCEL_FORMAT_ERROR + "'}"; } if (!System.IO.Directory.Exists(Server.MapPath(excelPath))) { System.IO.Directory.CreateDirectory(Server.MapPath(excelPath)); } fName = DateTime.Now.ToString("yyyyMMddhhmmss") + fo.Extension; filePath = Server.MapPath(excelPath) + "/" + fName; } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); return "{success:false,msg:'" + Resources.ProductItemMap.EXCEL_FORMAT_ERROR + "'}"; } try { Request.Files[0].SaveAs(filePath); } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); } IProductItemMapExcelImplMgr ife = new ProductItemMapExcelMgr(connectionString); List<ProductItemMapCustom> pm = new List<ProductItemMapCustom>(); try { List<ProductItemMapCustom> errorPm = new List<ProductItemMapCustom>(); Resource.CoreMessage = new CoreResource("ProductItemMap"); bool isHeaderError = false; //讀取excel裡賣弄的內容 pm = ife.ReadFile(filePath, channel_id, fExtension, ref isHeaderError, errorPm); if (!isHeaderError) { if (errorPm.Count == 0) { ife.SaveToDB(pm); } else { return "{success:true,error:true,path:'" + fName + "',data:" + JsonConvert.SerializeObject(errorPm) + "}"; } } else { return "{success:true,headerError:true}"; } } catch (Exception ex) { Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage(); logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message); logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name; log.Error(logMessage); return "{success:false,msg:'" + Resources.ProductItemMap.IMPORT_FAIL + "'}"; } return "{success:true,msg:'" + string.Format(Resources.ProductItemMap.IMPORT_SUCCESS_TOTAL, pm.Count) + "'}"; }