public void Add(string a) { using (StreamWriter writer = new StreamWriter(file.ToString(), true, System.Text.Encoding.Default)) { writer.WriteLine(DateTime.Now + " - " + a); } }
protected override void LoadData(System.IO.FileInfo xmlFile) { if (xmlFile.Exists) { taskFile = xmlFile; StreamReader projectsXmlFileReader = new StreamReader(xmlFile.ToString()); string projectsInXml = projectsXmlFileReader.ReadToEnd(); projectsXmlFileReader.Close(); List <Project> list = XmlSerializationHelper.Desirialize <List <Project> >(projectsInXml); lock (dataListLock) { foreach (Project obj in list) { dataList.Add(obj.pId, obj); } } Console.WriteLine("{0} File found. {1} Entries", xmlFile.ToString(), dataList.Count); } else { Console.WriteLine("todos.xml File not found."); } }
public static string GetFilePath(this OleMenuCommand command) { string filePath = String.Empty; command.Visible = false; command.Enabled = false; uint itemid = VSConstants.VSITEMID_NIL; IVsHierarchy hierarchy = null; if (!command.IsSingleProjectItemSelection(out hierarchy, out itemid)) return null; // Get the file path string itemFullPath = null; ((IVsProject)hierarchy).GetMkDocument(itemid, out itemFullPath); var transformFileInfo = new FileInfo(itemFullPath); string ext = Path.GetExtension(transformFileInfo.ToString().ToLower()); bool isProperExtension = false; if (Globals.FileTypes.ContainsKey(ext)) { isProperExtension = true; } filePath = transformFileInfo.ToString(); // if not leave the menu hidden if (!isProperExtension) return null; return filePath; }
internal static HttpPostedFileBase PrepareFakeWebInput(FileInfo file) { var fakeWebInput = A.Fake<HttpPostedFileBase>(); var stream = File.Open(file.ToString(), FileMode.Open); A.CallTo(() => fakeWebInput.InputStream).Returns(stream); A.CallTo(() => fakeWebInput.FileName).Returns(file.ToString()); return fakeWebInput; }
public void Worker() { directory[0].Create(); directory[1].Create(); file = new System.IO.FileInfo("C://for13lab//Inspect//dirinfo.txt"); Add("Создаем файл" + file.ToString()); Add("Записываем информацию о файлах и папках в " + file.ToString()); using (StreamWriter fs = new StreamWriter(file.ToString(), true, System.Text.Encoding.Default)) { foreach (string s in files) { fs.WriteLine(s); } foreach (string s in directories) { fs.WriteLine(s); } Console.WriteLine("Текст записан в файл."); } FileInfo newdirinfo = new FileInfo("C://for13lab//NEWdirinfo.txt"); if (!newdirinfo.Exists) { Add("Копируем dirinfo и удаляем его"); file.CopyTo("C://for13lab//NEWdirinfo.txt"); file.Delete(); } DirectoryInfo fotos = new DirectoryInfo("C://for13lab//Fotos"); Add("Получаем информацию о png файлах в " + fotos.ToString()); System.IO.FileInfo[] jpegFiles = fotos.GetFiles("*.png"); Add($"Копируем файлы png из {fotos.ToString()} в Inspect"); foreach (System.IO.FileInfo file in jpegFiles) { file.CopyTo("C://for13lab//Inspect//" + file.Name, true); } Add("Перемещаем " + directory[1].ToString() + " в " + directory[0].ToString()); directory[1].MoveTo("C://for13lab//Inspect//Files//"); //ZipFile.CreateFromDirectory(directory[0].ToString(), "C://myArchive.zip"); //ZipFile.ExtractToDirectory("C://myArchive.zip", "C://unzip"); Compress("C://for13lab/myfile.txt", "C://for13lab/file.gz"); Add("Файл сжат"); Decompress("C://for13lab/file.gz", "C://for13lab/Unarchived.txt"); Add("Файл восстановлен"); }
private void GearInspectorReadWriteSettings(bool read) { try { FileInfo GearInspectorSettingsFile = new FileInfo(GearDir + @"\GearInspector.xml"); if (read) { try { if (!GearInspectorSettingsFile.Exists) { try { string filedefaults = GetResourceTextFile("GearInspector.xml"); using (StreamWriter writedefaults = new StreamWriter(GearInspectorSettingsFile.ToString(), true)) { writedefaults.Write(filedefaults); writedefaults.Close(); } } catch (Exception ex) { LogError(ex); } } using (XmlReader reader = XmlReader.Create(GearInspectorSettingsFile.ToString())) { XmlSerializer serializer = new XmlSerializer(typeof(GearInspectorSettings)); GISettings = (GearInspectorSettings)serializer.Deserialize(reader); reader.Close(); } } catch { GISettings = new GearInspectorSettings(); } } if(!read) { if(GearInspectorSettingsFile.Exists) { GearInspectorSettingsFile.Delete(); } using (XmlWriter writer = XmlWriter.Create(GearInspectorSettingsFile.ToString())) { XmlSerializer serializer2 = new XmlSerializer(typeof(GearInspectorSettings)); serializer2.Serialize(writer, GISettings); writer.Close(); } } }catch(Exception ex){LogError(ex);} }
private void CombatHudReadWriteSettings(bool read) { try { FileInfo GearTacticianSettingsFile = new FileInfo(GearDir + @"\GearTactician.xml"); if (read) { try { if (!GearTacticianSettingsFile.Exists) { try { using (XmlWriter writer = XmlWriter.Create(GearTacticianSettingsFile.ToString())) { XmlSerializer serializer2 = new XmlSerializer(typeof(GearTacticianSettings)); serializer2.Serialize(writer, gtSettings); writer.Close(); } } catch (Exception ex) { LogError(ex); } } using (XmlReader reader = XmlReader.Create(GearTacticianSettingsFile.ToString())) { XmlSerializer serializer = new XmlSerializer(typeof(GearTacticianSettings)); gtSettings = (GearTacticianSettings)serializer.Deserialize(reader); reader.Close(); } } catch { gtSettings = new GearTacticianSettings(); } } if(!read) { if(GearTacticianSettingsFile.Exists) { GearTacticianSettingsFile.Delete(); } using (XmlWriter writer = XmlWriter.Create(GearTacticianSettingsFile.ToString())) { XmlSerializer serializer2 = new XmlSerializer(typeof(GearTacticianSettings)); serializer2.Serialize(writer, gtSettings); writer.Close(); } } }catch(Exception ex){LogError(ex);} }
//import pgp public key private void Button6_Click(object sender, EventArgs e) { var FD = new OpenFileDialog(); if (FD.ShowDialog() == DialogResult.OK) { System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName); Properties.Settings.Default.public_key = File.ToString(); Properties.Settings.Default.Save(); Status("\nAdded pub key ->" + File.ToString()); CheckList[1] = 1; } }
public CodeEditor(System.IO.FileInfo file) { this.InitializeComponent(); this.CodeType = CodeEditor.CodeDocumentType.Css; this.FileName = file.ToString(); this.TextBox_Filename.Text = System.IO.Path.GetFileName(file.ToString()); this.IsNewFile = false; this.TextBox_Filename.IsReadOnly = true; this.TextBox_Filename.Background = new SolidColorBrush(Colors.LightGray); this.TextBox_Filename.Foreground = new SolidColorBrush(Colors.DimGray); this.LoadTextFile(file.ToString()); this.StandardInit(); this.Editor.Focus(); }
void addLastTime(FileInfo file) { if (!file.Exists) return; lock (m_syncOjbect) { if (wordsLastTime.ContainsKey(file.ToString())) { wordsLastTime[file.ToString()] = file.LastWriteTime.ToFileTime(); } else { wordsLastTime.Add(file.ToString(), file.LastWriteTime.ToFileTime()); } } }
public override void setUp() { base.setUp(); _home = new DirectoryInfo(Path.Combine(trash.ToString(), "home")); _configFile = new FileInfo(Path.Combine(_home.ToString(), ".ssh")); Directory.CreateDirectory(_configFile.ToString()); _configFile = new FileInfo(Path.Combine(_configFile.ToString(), "config")); // can't do //Environment.UserName = "******"; _osc = new OpenSshConfig(_home, _configFile); }
private void btSend_Click(object sender, EventArgs e) { if (lbBoxOnline.CheckedItems.Count == 0) { App.MsgBoxE(Resource1.not_select_box); return; } if (App.MsgBox2(Resource1.send_to_box, Resource1.notice) != DialogResult.OK) { return; } if (doCreateZip()) { long length = new System.IO.FileInfo(App.ZipPath).Length; foreach (var item in lbBoxOnline.CheckedItems) { Box box = item as Box; byte[] b = Cmd.create(Command.send_ad, length.ToString()); box.CmdChan.send(b); } FileChannel.BoxCount = lbBoxOnline.CheckedItems.Count; FileChannel.Done = 0; showSendData(FileChannel.BoxCount); } }
public void ProcessDirectory(string origpath, string path, int index, ref StreamWriter sw) { // Process the list of files found in the directory. string[] fileEntries = Directory.GetFiles(path); foreach (string fileName in fileEntries) { //for (int i = 0; i < index; i++) //{ // sw.Write("\t"); //} string test = fileName.TrimStart(origpath.ToCharArray()); long a = new System.IO.FileInfo(fileName).Length; sw.WriteLine(test + " " + a.ToString()); } // Recurse into subdirectories of this directory. string[] subdirectoryEntries = Directory.GetDirectories(path); foreach (string subdirectory in subdirectoryEntries) { //for (int i = 0; i <= index; i++) //{ // sw.Write("\t"); //} //string test = subdirectory.TrimStart(origpath.ToCharArray()); //sw.WriteLine(test); ProcessDirectory(origpath, subdirectory, index + 1, ref sw); } }
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"); }
private void BT_Convertir_Click(object sender, EventArgs e) { string pthFile; openFileDialog_FindFile.ShowDialog(); System.IO.FileInfo fInfo = new System.IO.FileInfo(openFileDialog_FindFile.FileName); pthFile = fInfo.ToString(); try { string xmlText = System.IO.File.ReadAllText(pthFile); if (pthFile.Contains(".xml") == false) { MessageBox.Show("El fichero tiene que ser de tipo .XML", "Ese tipo de fichero no vale", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } else { ReadXML(xmlText); UpdateOriginID(); if (!ValidateCSV()) { WriteCSV(); } } } catch { //Por si le das a cancelar al buscar el fichero } }
/// <summary> /// 建置Execl /// </summary> /// <param name="path"></param> public string CreatExcel() { #region 模擬寫入table var _MastTable = new DataTable(); //加入欄位名稱 _MastTable.Columns.Add("欄位一"); _MastTable.Columns.Add("欄位二"); _MastTable.Columns.Add("欄位三"); _MastTable.Columns.Add("欄位四"); _MastTable.AcceptChanges(); //塞入資料 var rand = new Random(); for (int j = 0; j < 10; j++) { var newRow = _MastTable.NewRow(); newRow["欄位一"] = string.Format("{0}", j + 1 * rand.Next(0, 100)); newRow["欄位二"] = string.Format("{0}", j + 1 * rand.Next(0, 100)); newRow["欄位三"] = string.Format("{0}", j + 1 * rand.Next(0, 100)); newRow["欄位四"] = string.Format("{0}", j + 1 * rand.Next(0, 100)); _MastTable.Rows.Add(newRow); } #endregion string sid = DateTime.Now.ToString("yyyyMMddHHmmss"); var path = _env.ContentRootPath + "/wwwroot/暫存區/" + sid + ".xlsx"; System.IO.FileInfo filePath = new System.IO.FileInfo(path); if (!System.IO.File.Exists(filePath.ToString())) { ExcelPackage.LicenseContext = LicenseContext.NonCommercial; //建立一筆新的Excel文件 ExcelPackage ep = new ExcelPackage(); //產生頁籤 ExcelWorksheet sheet = ep.Workbook.Worksheets.Add("資料表"); //塞入table sheet.Cells.LoadFromDataTable(_MastTable, true); #region 手動塞入寫法 ////塞標頭欄位 //for (int j = 0; j < _MastTable.Columns.Count; j++) //{ // //只印出此次補號的前幾筆 // sheet.Cells[1, j + 1].Value = _MastTable.Columns[j]; //} ////塞資料 //for (int i = 0; i < _MastTable.Rows.Count; i++) //{ // for (int j = 0; j < _MastTable.Columns.Count; j++) // { // sheet.Cells[i + 1, j + 1].Value = _MastTable.Rows[i][j].ToString(); // } //} #endregion //建立文件 ep.SaveAs(new FileInfo(path)); } return("OK"); }
private void metroButton1_Click(object sender, EventArgs e) { System.Windows.Forms.FolderBrowserDialog chooseFiles = new System.Windows.Forms.FolderBrowserDialog(); if (chooseFiles.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fileList.Items.Clear(); string[] files = Directory.GetFiles(chooseFiles.SelectedPath); foreach (string file in files) { string fileName = Path.GetFileNameWithoutExtension(file); string extension = Path.GetExtension(file); string path = Path.GetFullPath(file); ListViewItem item = new ListViewItem(fileName); item.SubItems.Add(path); item.SubItems.Add(extension); long size = new System.IO.FileInfo(file).Length; item.SubItems.Add(size.ToString()); item.SubItems.Add("ready"); item.Tag = file; fileList.Items.Add(item); } } else { MessageBox.Show("Alert", "non selected"); } }
public void SaveSettings() { DirectoryInfo SettingsFolder = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\Decal Plugins\Gleaner\Settings"); FileInfo SettingsFile = new FileInfo(SettingsFolder.FullName + @"\Settings.xml"); FileInfo KeyFile = new FileInfo(SettingsFolder.FullName + @"\Keys.xml"); using(XmlWriter writer = XmlWriter.Create(SettingsFile.ToString())) { bool[] operationflags = new bool[2]; gleaneron = operationflags[0] = gleaneron; operationflags[1] = gleanerreport; XmlSerializer serializer = new XmlSerializer(typeof(bool[])); serializer.Serialize(writer, operationflags); writer.Close(); } using (XmlWriter writer2 = XmlWriter.Create(KeyFile.ToString())) { XmlSerializer serializer2 = new XmlSerializer(typeof(KeyClass)); serializer2.Serialize(writer2, MasterKeyClass); writer2.Close(); } CoreManager.Current.Actions.AddChatText(("Settings Saved."), 9, 5); }
private void btnFileUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.ShowDialog(); string FilePath = openFileDialog.FileName; MessageBox.Show(FilePath); string filesize = ""; long size = new System.IO.FileInfo(FilePath).Length; filesize = size.ToString(); var stopwatch = new Stopwatch(); txtFileSize.Text = filesize; stopwatch.Start(); // string str = ""; stopwatch.Stop(); var stopwatch2 = new Stopwatch(); stopwatch2.Start(); var fileStream = new System.IO.FileStream(FilePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read); string str2 = GetChecksumBuffered(fileStream); txtHash.Text = str2; long a = stopwatch2.ElapsedMilliseconds; string responsetime = ""; responsetime = a.ToString(); txtResponseTime.Text = responsetime; }
public List<List<Double>> GetData(FileInfo infile) { StreamReader sr = new StreamReader(infile.ToString()); string Line = null; string subline; List<List<double>> Table = new List<List<double>>(); if (!infile.Exists) Console.WriteLine(@"Can't find Files! "); Line = sr.ReadLine(); while ((Line = sr.ReadLine()) != null){ Line = Line + ","; List<double> sample = new List<double>(); while (Line.Contains(",")){ subline = Line.Substring(0, Line.IndexOf(",")); sample.Add(Double.Parse(subline)); Line = Line.Substring(Line.IndexOf(",") + 1, Line.Length - Line.IndexOf(",") - 1); }//one line finish Table.Add(sample); } //Transaction of Attributes /* for (int i = 1; i < Table[0].Count();i++){ List<double> sampleT = new List<double>(); for (int j = 0; j < Table.Count(); j++) { sampleT.Add(Table[j][i]); } Attributes.Add(sampleT); }*/ return Table; }
/// <summary> /// Round up and downsample from 8bit to 4bit PCM /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCrunch_Click(object sender, EventArgs e) { string inputFile = tbFile.Text; string outputFile = ""; long outputFileSize = -1; if (File.Exists(inputFile)) { outputFile = crunchFile(inputFile); tbFile.Text = outputFile; if (File.Exists(outputFile)) { outputFileSize = new System.IO.FileInfo(outputFile).Length; } long inputFileSize = new System.IO.FileInfo(inputFile).Length; tbStatus.Text += Environment.NewLine; tbStatus.Text += "Crunch 8bit PCM to packed 4bit PCM (_CRN)" + Environment.NewLine; tbStatus.Text += "Input file size (bytes): " + inputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Ouput file size (bytes): " + outputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Done" + Environment.NewLine; } else { tbStatus.Text += "Input file does not exist!"; } }
protected void Page_Load(object sender, EventArgs e) { string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); if(oInfo.ToString() == "/history/Default.aspx") LiteralAudio.Text = "so.addVariable('audioPlay', 'false');" ; }
/// <summary> /// RLE Compress file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCompress_Click(object sender, EventArgs e) { string inputFile = tbFile.Text; string outputFile = ""; long outputFileSize = -1; if (File.Exists(inputFile)) { List <int> value = new List <int>(); outputFile = rleCompress(inputFile, ref value); tbFile.Text = outputFile; // update file name text box if (File.Exists(outputFile)) { outputFileSize = new System.IO.FileInfo(outputFile).Length; } long inputFileSize = new System.IO.FileInfo(inputFile).Length; tbStatus.Text += Environment.NewLine; tbStatus.Text += "RLE compress 4bit packed PCM (_RLE)" + Environment.NewLine; tbStatus.Text += "Input file size (bytes): " + inputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Number of nibble clusters: " + value.Count + Environment.NewLine; tbStatus.Text += "Nibble clusters size (bytes): " + (value.Count * 2) + Environment.NewLine; tbStatus.Text += "Total nibbles in clusters: " + value.Sum() + Environment.NewLine; tbStatus.Text += "Total bytes in clusters: " + value.Sum() / 2 + Environment.NewLine; tbStatus.Text += "Output file size (bytes): " + outputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Done" + Environment.NewLine; } else { tbStatus.Text += "Input file does not exist!"; } }
/// <summary> /// Decompress RLE encoded file, used as a test /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDecompress_Click(object sender, EventArgs e) { string inputFile = tbFile.Text; string outputFile = ""; long outputFileSize = -1; if (File.Exists(inputFile)) { outputFile = rleDecompress(inputFile); tbFile.Text = outputFile; // update file name text box if (File.Exists(outputFile)) { outputFileSize = new System.IO.FileInfo(outputFile).Length; } long inputFileSize = new System.IO.FileInfo(inputFile).Length; tbStatus.Text += Environment.NewLine; tbStatus.Text += "RLE decompress 4bit packed PCM (_ELR)" + Environment.NewLine; tbStatus.Text += "Input file size (bytes): " + inputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Output file size (bytes): " + outputFileSize.ToString() + Environment.NewLine; tbStatus.Text += "Done" + Environment.NewLine; } else { tbStatus.Text += "Input file does not exist!"; } }
/// <summary> /// Retrieves a template from the system, compiling it if needed. /// </summary> public ITemplate this[FileInfo file] { get { // Check the hash ITemplate template = (ITemplate) templates[file.FullName]; if (template != null) return template; // Ignore blanks if (!file.Exists) { throw new TemplateException("File does not exist: " + file); } // Create the template Debug("Parsing template: " + file); TextReader reader = file.OpenText(); template = factory.Create(reader, file.ToString()); reader.Close(); // Save the template and return it templates[file.FullName] = template; return template; } }
public void TestToString() { var a = new ZlpFileInfo(@"C:\ablage\test.txt"); var b = new FileInfo(@"C:\ablage\test.txt"); var x = a.ToString(); var y = b.ToString(); Assert.AreEqual(x,y); // -- a = new ZlpFileInfo(@"C:\ablage\"); b = new FileInfo(@"C:\ablage\"); x = a.ToString(); y = b.ToString(); Assert.AreEqual(x,y); // -- a = new ZlpFileInfo(@"test.txt"); b = new FileInfo(@"test.txt"); x = a.ToString(); y = b.ToString(); Assert.AreEqual(x,y); // -- a = new ZlpFileInfo(@"c:\ablage\..\ablage\test.txt"); b = new FileInfo(@"c:\ablage\..\ablage\test.txt"); x = a.ToString(); y = b.ToString(); Assert.AreEqual(x,y); // -- a = new ZlpFileInfo(@"\ablage\test.txt"); b = new FileInfo(@"\ablage\test.txt"); x = a.ToString(); y = b.ToString(); Assert.AreEqual(x,y); // -- a = new ZlpFileInfo(@"ablage\test.txt"); b = new FileInfo(@"ablage\test.txt"); x = a.ToString(); y = b.ToString(); Assert.AreEqual(x,y); }
static void Main(string[] args) { string sInFile = @"D:\Downloads\fredda johnson interview.flac"; var Lenght = GetFileSeconds(sInFile); Console.WriteLine("Len " + Lenght.ToString()); var Weight = new System.IO.FileInfo(sInFile).Length; Console.WriteLine("weight " + Weight.ToString()); var ArrayOfSizes = GetArrayOfLenghts(Lenght, 60);//GetArrayOfSizes(Lenght, Weight, 10000000); ArrayOfSizes.ForEach(x => Console.WriteLine(x)); Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"D:\Downloads\clave.json"); var SplitFiles = SplitFileToolKit(sInFile, ArrayOfSizes); SplitFiles.ForEach(x => Console.WriteLine(x)); if (File.Exists(sOutFile)) { File.Delete(sOutFile); } foreach (var sFile in SplitFiles) { File.AppendAllText(sOutFile, STT(sFile)); } Console.Read(); }
public static void SetRandomWallpaperFromPath(FileInfo file, Style style) { if (file == null) return; SystemParametersInfo(SetDesktopWallpaper, 0, file.ToString(), UpdateIniFile | SendWinIniChange); var key = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", true); if (key == null) return; switch (style) { case Style.Stretch: key.SetValue(@"WallpaperStyle", "2"); key.SetValue(@"TileWallpaper", "0"); break; case Style.Center: key.SetValue(@"WallpaperStyle", "1"); key.SetValue(@"TileWallpaper", "0"); break; case Style.Tile: key.SetValue(@"WallpaperStyle", "1"); key.SetValue(@"TileWallpaper", "1"); break; case Style.NoChange: break; } key.Close(); }
public void CompareBins() { try { long fsize = new System.IO.FileInfo(txtBaseFile.Text).Length; long fsize2 = new System.IO.FileInfo(txtModifierFile.Text).Length; if (fsize != fsize2) { MessageBox.Show("Files are different size, will not compare!"); return; } if (fsize != (uint)512 * 1024 && fsize != (1024 * 1024)) { MessageBox.Show("Unknown file size (" + fsize.ToString() + "),will not compare!"); return; } byte[] BaseFile = new byte[fsize]; byte[] ModifierFile = new byte[fsize]; PatchAddr = new List <uint>(); PatchData = new List <uint>(); BasePCM = new PCMData(); ModPCM = new PCMData(); GetPcmType(txtBaseFile.Text, ref BasePCM); GetPcmType(txtModifierFile.Text, ref ModPCM); uint BaseOS = GetOsidFromFile(txtBaseFile.Text); uint ModOS = GetOsidFromFile(txtModifierFile.Text); if (BaseOS != ModOS) { MessageBox.Show("File1 OS = " + BaseOS.ToString() + ", File2 OS = " + ModOS.ToString() + Environment.NewLine + "Will not compare!", "OS Mismatch"); return; } BaseFile = ReadBin(txtBaseFile.Text, 0, (uint)fsize); GetSegmentAddresses(BaseFile, ref BasePCM); labelOS.Text = BasePCM.Segments[1].PN.ToString(); ModifierFile = ReadBin(txtModifierFile.Text, 0, (uint)fsize); txtResult.Text = ""; for (int s = 1; s <= 9; s++) { if (chkSegments[s].Enabled && chkSegments[s].Checked) { Logger("Comparing segment " + SegmentNames[s]); CompareSegment(BasePCM.Segments[s].Start, BasePCM.Segments[s].Length, BaseFile, ModifierFile); if (s == 1) //If OS is selected, compare OS2 segment, too { CompareSegment(BasePCM.Segments[0].Start, BasePCM.Segments[0].Length, BaseFile, ModifierFile); } } } } catch (Exception ex) { Logger("Error: " + ex.Message); } }
private void InitializeRole(FileInfo file) { XmlDocument xml = new XmlDocument(); xml.Load(file.ToString()); XmlElement root=xml.DocumentElement; List<Operate> operates = new List<Operate>(); Dictionary<int, string> operatesDic = new Dictionary<int, string>(); foreach(XmlNode node in root.GetElementsByTagName("operates")){ foreach (XmlNode n in node.SelectNodes("operate")) { Operate operate = new Operate(); operate.Name = n.Attributes["name"].Value.ToString(); operate.Value = Convert.ToInt32(n.Attributes["value"].Value.ToString()); operates.Add(operate); operatesDic.Add(Convert.ToInt32(n.Attributes["value"].Value.ToString()), n.Attributes["url"].Value.ToString()); } } this.Operates = operates; List<Menu> menus = new List<Menu>(); foreach (XmlNode node in root.GetElementsByTagName("menus")) { foreach (XmlNode menuNode in node.SelectNodes("menu")) { Menu menu = new Menu(); List<SubMenu> subMenus = new List<SubMenu>(); foreach (XmlNode subNode in menuNode.SelectNodes("submenu")) { SubMenu subMenu = new SubMenu(); List<Item> items = new List<Item>(); Dictionary<int, string> Urls = new Dictionary<int, string>(); subMenu.Name = subNode.Attributes["name"].Value.ToString(); subMenu.Value = Convert.ToInt32(subNode.Attributes["value"].Value.ToString()); foreach (XmlNode nodeItem in subNode.SelectNodes("item")) { Item item = new Item(); item.Name = nodeItem.Attributes["name"].Value.ToString(); item.Value = Convert.ToInt32(nodeItem.Attributes["value"].Value); item.Operates = nodeItem.Attributes["operates"].Value.ToString(); item.Url = nodeItem.Attributes["url"].Value.ToString(); items.Add(item); if (item.Operates != null) { string[] operateArray = (nodeItem.Attributes["operates"].Value.ToString()).Split(','); foreach (string operateStr in operateArray) { // if(Convert.toi) } } Urls.Add(Convert.ToInt32(nodeItem.Attributes["value"].Value), nodeItem.Attributes["url"].Value.ToString()); } menu.Name = menuNode.Attributes["name"].Value.ToString(); menu.Value = Convert.ToInt32(menuNode.Attributes["value"].Value); subMenu.Items = items; subMenus.Add(subMenu); menu.SubMenus = subMenus; } menus.Add(menu); } this.Menus = menus; } this.InitializeMessage = "文件初始化完毕!"; this.InitializeSuccess = true; }
static void CheckDirInfo(string[] args) { fDirInfo = new FileInfo(args[0]); try { Sortdir = args[1]; } catch (Exception) { Sortdir = @"C:\Sort\"; } Console.WriteLine("Папка с отсортированными файлами = {0} \n(Нажмите любую кнопку для начала сортировки)", Sortdir); Console.ReadKey(); DirInfo = GetDirInfo(); string diend = String.Format("{0}{1}", DirInfo.FullName, "\u005c"); if (fDirInfo.ToString().CompareTo(diend) != 0) { Console.WriteLine(@"А гдэ '\' в конце?"); Console.Write(@"Выбранная директория: {0} [ Y/N/'Any key' ] ( 'N' перейти в = {1}\ 'Any key' - Выход ) ", DirInfo.FullName, fDirInfo.ToString()); string yn = Console.ReadLine(); switch (yn) { case "y": case "Y": break; case "n": case "N": diend = null; args[0] = String.Format("{0}{1}", fDirInfo.ToString(), "\u005c"); CheckDirInfo(SetArgs); break; default: Exit(); break; } } }
/// <summary> /// Serializes the current instance of the Author class. /// </summary> public void Serialize() { string fileName = string.Format(@"C:\Users\Viktor\Desktop\GitHub\HackBulgaria-CSharp\Week 8\TEST\" + this.Name + " Serialized.txt"); FileInfo file = new FileInfo(fileName); using (FileStream s = new FileStream(file.ToString(), FileMode.Create, FileAccess.ReadWrite)) { BinaryFormatter b = new BinaryFormatter(); b.Serialize(s, this); } }
/// <summary> /// Get the filename, without extension. /// </summary> /// <param name="file">The file to parse.</param> /// <returns>The file name.</returns> public static String GetFileName(FileInfo file) { String fileName = file.ToString(); int mid = fileName.LastIndexOf("."); if (mid == -1) { return fileName; } return fileName.Substring(0, (mid) - (0)); }
/// <summary> /// Converts source file .doc,.xls,.ppt to .pdf adobe reader files and also adds watermark on top of PDF file /// </summary> /// <param name="sourceFile">Specify your source file with extension .doc(x), .xls(x), .ppt(x)</param> /// <param name="targetPath"></param> /// <param name="isWaterMarked"></param> /// <param name="currentPage"></param> /// <param name="originalDocumentName"></param> /// <returns></returns> public static int Process(FileInfo sourceFile, FileInfo targetPath, bool isWaterMarked, int currentPage, string originalDocumentName,int qualitySet) { LoadLicense(sourceFile.Extension.ToUpper()); var pageCount = Strategies[sourceFile.Extension.ToUpper()].Process(sourceFile.FullName, targetPath.FullName, currentPage, originalDocumentName, qualitySet); var targetFileName = targetPath.ToString().PathSplit(); var targetFileExt = targetFileName[targetFileName.Length - 1].Split('.'); var imageFile = targetPath.ToString().Replace("." + targetFileExt[targetFileExt.Length - 1], string.Empty) + currentPage + ConfigurationManager.AppSettings["ImageExtension"]; if (isWaterMarked) ApplytWaterMark(imageFile); var databaseHelper = new DatabaseHelper(); var appKey = databaseHelper.GetApplicationKey(Path.GetFileNameWithoutExtension(sourceFile.Name)); appKey.StatusId = (int)EnumStatus.Completed; appKey.PageCount = pageCount; databaseHelper.UpdateApplicationKey(appKey); return pageCount; }
private static void PublishTestDb(FileInfo mdfFile, FileInfo ldfFile, string targetDbPath) { var targetMdfFile = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + targetDbPath); var targetLdfFile = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + targetDbPath.Replace(".mdf", "_log.ldf")); if (targetMdfFile.Exists) targetMdfFile.Delete(); if (targetLdfFile.Exists) targetLdfFile.Delete(); mdfFile.MoveTo(targetMdfFile.ToString()); ldfFile.MoveTo(targetLdfFile.ToString()); }
internal void SslBlackList(FileInfo mfile) { string path = Common.GetPath(); //FileUrl = Common.GetURL();// Creates a dictionary of Filename and URL from which it got downloaded using (var rd = new StreamReader(path + mfile.ToString())) { List<KeyValuePair<string, List<string>>> InfoList = new List<KeyValuePair<string, List<string>>>(); string fieldC = "category"; string fieldD = "description"; string fieldU = "url"; string fieldT = "date"; string IP = ""; string IpDescription = ""; string category = ""; string IpDate = ""; string URL = ""; string line1 = rd.ReadLine(); string line2 = rd.ReadLine(); string line3 = rd.ReadLine(); while (!rd.EndOfStream) { string line = rd.ReadLine(); string[] info = line.Split(','); IpDate = line3.Split(':')[1]; if (info.Count() == 3) { IP = info[0]; IpDescription = info[2]; category = "C & C"; URL = "https://sslbl.abuse.ch"; DescriptionList.Add(IpDescription); CategoryList.Add(category); UrlList.Add(URL); IpDateList.Add(IpDate); InfoList.Add(new KeyValuePair<string, List<string>>(fieldC, CategoryList)); InfoList.Add(new KeyValuePair<string, List<string>>(fieldD, DescriptionList)); InfoList.Add(new KeyValuePair<string, List<string>>(fieldU, UrlList)); InfoList.Add(new KeyValuePair<string, List<string>>(fieldT, IpDateList)); if (!BlackListDB.ContainsKey(IP)) { BlackListDB.Add(IP, InfoList); totalip.Add(IP); } CategoryList = new List<string>(); DescriptionList = new List<string>(); UrlList = new List<string>(); InfoList = new List<KeyValuePair<string, List<string>>>(); IpDateList = new List<string>(); } } } }
public static FileInfo GetPrivateApplicationBaseFileFor(Artifact artifact, DirectoryInfo localRepository, string currentDir) { FileInfo target = new FileInfo(currentDir + Path.PathSeparator + "target" + Path.PathSeparator+artifact.ArtifactId + artifact.Extension); FileInfo source = GetUserAssemblyCacheFileFor(artifact, localRepository); if(source.Exists) { File.Copy( source.ToString(), target.ToString()); } return target; }
static internal int ExtractTileNumber(string prefix, System.IO.FileInfo info) { Regex re = TileReader.GetTileFilenameRegEx(prefix, info); Match match = re.Match(info.ToString()); // 2 because match.Groups[0] is entire match if (match.Groups.Count != 2) { return(-1); } return(Convert.ToInt32(match.Groups[1].Captures[0].Value)); }
private static string CallOcrWebService(FileInfo pngFile, int topLeftX, int topLeftY, int bottomRightX, int bottomRightY) { var restClient = new RestServiceClient { Proxy = { Credentials = CredentialCache.DefaultCredentials }, ApplicationId = ConfigurationManager.AppSettings["ApplicationId"].ToString(), Password = ConfigurationManager.AppSettings["Password"].ToString() }; var textFieldProcessingSettings = new TextFieldProcessingSettings { CustomOptions = "region=" + topLeftX + "," + topLeftY + "," + bottomRightX + "," + bottomRightY, Language = "english" }; if (pngFile.DirectoryName == null) throw new Exception("png file directory name is blank"); var outputXmlFile = Path.Combine(pngFile.DirectoryName, GetFileNameWithoutExtension(pngFile) + ".xml"); // call the REST service var task = restClient.ProcessTextField(pngFile.ToString(), textFieldProcessingSettings); System.Threading.Thread.Sleep(4000); task = restClient.GetTaskStatus(task.Id); //Console.WriteLine("Task status: {0}", task.Status); while (task.IsTaskActive()) { // Note: it's recommended that your application waits // at least 2 seconds before making the first getTaskStatus request // and also between such requests for the same task. // Making requests more often will not improve your application performance. // Note: if your application queues several files and waits for them // it's recommended that you use listFinishedTasks instead (which is described // at http://ocrsdk.com/documentation/apireference/listFinishedTasks/). System.Threading.Thread.Sleep(4000); task = restClient.GetTaskStatus(task.Id); //Console.WriteLine("Task status: {0}", task.Status); } if (task.Status == TaskStatus.Completed) { //Console.WriteLine("Processing completed."); restClient.DownloadResult(task, outputXmlFile); //Console.WriteLine("Download completed."); } else { //Console.WriteLine("Error while processing the task"); return outputXmlFile; } return outputXmlFile; }
public void listAllFiles(ref List<string> inFiles) { string error1 = "[wiff] <Exception>: Failed to find file."; string error2 = "[wiff] <Exception>: Warning: No wiff files."; for (int i = 0; i < inFiles.Count(); i++) { //判断为单个文件还是路径 if (!Directory.Exists(inFiles[i]) && !File.Exists(inFiles[i])) { //既不是文件也不是路径,退出 Console.WriteLine("{0} {1}", error1, inFiles[i]); Environment.Exit(0); //Application.Exit(); } else if (File.Exists(inFiles[i])) { //是文件,检查是否以 wiff结尾 FileInfo fi = new FileInfo(inFiles[i]); if (fi.Extension.ToUpper().CompareTo(".WIFF") == 0) { inputfiles.Add(fi.ToString());//文件名都以.wiff结尾 } } else if (Directory.Exists(inFiles[i])) { //是路径,检查路径中是否有 wiff结尾 bool haswiff = false; DirectoryInfo folder = new DirectoryInfo(inFiles[i]); foreach (FileInfo tmpfi in folder.GetFiles()) { if (tmpfi.Extension.ToUpper().CompareTo(".WIFF") == 0) { haswiff = true; string filepath = inFiles[i] + "\\" + tmpfi; inputfiles.Add(filepath); } } if (haswiff == false) { Console.WriteLine("[wiff] <Exception>: Find no wiffs in "+inFiles[i]+"!"); } } } if (inputfiles.Count == 0) { Console.WriteLine(error2); Environment.Exit(0); // Application.Exit(); } }
private void CheckIfPublicKeyExists() { if (!File.Exists(Properties.Settings.Default.public_key)) { MessageBox.Show("Public key can not be found! , please show me the way..\n", "Error!"); var FD = new OpenFileDialog(); if (FD.ShowDialog() == DialogResult.OK) { FileInfo File = new System.IO.FileInfo(FD.FileName); Properties.Settings.Default.public_key = File.ToString(); Properties.Settings.Default.Save(); } } }
protected override void LoadData(System.IO.FileInfo xmlFile) { if (xmlFile.Exists) { StreamReader projectsXmlFileReader = new StreamReader(xmlFile.ToString()); string projectsInXml = projectsXmlFileReader.ReadToEnd(); projectsXmlFileReader.Close(); List <Todo> list = XmlSerializationHelper.Desirialize <List <Todo> >(projectsInXml); lock (dataListLock) { foreach (Todo obj in list) { dataList.Add(obj.pId, obj); } } RaiseLogEvent(LogType.Info, string.Format("{0} File found. {1} Entries", xmlFile.ToString(), dataList.Count)); } else { RaiseLogEvent(LogType.Error, string.Format("{0} File not found.", xmlFile.ToString())); } }
//Uploads files to Azure Storage Cloud in specified directories. Allows 10 simultaneous threads for uploading public void UploadBlob(string fileToUpload, string directory, string userID, string fileComments) { //ProgressBar progressBar = InitiateProgressBar("Uploading Files...", filesToUpload.Count); //int count = 1; BlobRequestOptions parallelThreadCountOptions = new BlobRequestOptions { ParallelOperationThreadCount = 10 }; if (File.Exists(fileToUpload)) { long fileSize = new System.IO.FileInfo(fileToUpload).Length; byte[] fileContent = ReadFile(fileToUpload); string blobName = directory + @"\" + Path.GetFileName(fileToUpload); var blob = blobContainer.GetBlockBlobReference(blobName); try { //Allow simultaneous I/O operations to help with large files blob.UploadFromByteArray(fileContent, 0, fileContent.Length); //Set file info for blob: blob name, file name, blob status, file comments, upload date/time, delete date/time, //recover date/time, file size, uploaded by, deleted by, recovered by blob.Metadata.Add(_blobNameKey, blob.Name); blob.Metadata.Add(_fileNameKey, Path.GetFileName(fileToUpload)); blob.Metadata.Add(_blobStatusKey, "Active"); blob.Metadata.Add(_fileCommentsKey, fileComments); blob.Metadata.Add(_uploadDateKey, DateTime.UtcNow.ToString()); blob.Metadata.Add(_deleteDateKey, "N/A"); blob.Metadata.Add(_recoverDateKey, "N/A"); blob.Metadata.Add(_fileSizeKey, fileSize.ToString()); blob.Metadata.Add(_uploadKey, userID); blob.Metadata.Add(_deleteKey, "N/A"); blob.Metadata.Add(_recoverKey, "N/A"); blob.SetMetadata(); //Create a snapshot for blob versioning blob.Snapshot(); } catch (Exception ex) { throw new ArgumentException(ex.Message); } } else { throw new ArgumentException("File does not exist"); } }
public FrmReportViewer(FileInfo pFile, DataSet dataset,List<ReportParameter> rparam) { InitializeComponent(); _file = pFile; _rParam = rparam; _dataset = dataset; reportViewer1.ProcessingMode = ProcessingMode.Local; reportViewer1.LocalReport.ReportPath = _file.ToString(); reportViewer1.LocalReport.SetParameters(_rParam); reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", _dataset.Tables[0])); reportViewer1.SetDisplayMode(DisplayMode.PrintLayout); reportViewer1.LocalReport.Refresh(); }
// Use this for initialization void Start() { targetTime = 5.0f; trackedObject = GetComponent <SteamVR_TrackedObject>(); // Get the hand componenet _hand = GetComponent <Hand>(); // Set the controller reference // device = _hand.controller; System.IO.FileInfo fi = new System.IO.FileInfo(@"D:\\3Levelfreq.csv"); if (File.Exists(fi.ToString())) { fi.Delete(); } // ThreeLevelHorizontal.startTheGame(); }
private void writeConfig(string dat) { FileInfo f = new FileInfo(Path.Combine(db.Directory.ToString(), "config")); FileStream stream = new FileStream(f.ToString(), System.IO.FileMode.Append); try { byte[] data = Encoding.UTF8.GetBytes(dat); stream.Write(data, 0, data.Length); } finally { stream.Close(); } db.Config.Load(); }
//wybieranie pliku private void button_Click(object sender, RoutedEventArgs e) { OpenFileDialog op = new OpenFileDialog(); op.DefaultExt = ".txt"; bool?result = op.ShowDialog(); if (result.HasValue) { FileNameText.Text = op.FileName; long length = new System.IO.FileInfo(FileNameText.Text).Length; length /= 1000; infoBox.Text += "Wybrano plik " + op.FileName + " (" + length.ToString() + " KB)\n"; } }
/// <summary> /// Runs on app close /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainMenu_FormClosed(object sender, FormClosedEventArgs e) { long fileLength = new System.IO.FileInfo(logFile).Length; long maxLength = Int64.Parse(logFileMaxSize); if (fileLength > maxLength) { File.Delete(logFile); } else { Log.WriteLog("Your log File size is: " + fileLength.ToString() + " BYTES!"); } Log.WriteLog("===============End Log===============\n"); }
public static string checkLogFileSize() { int year = DateTime.Today.Year; int month = DateTime.Today.Month; int day = DateTime.Today.Day; int hour = DateTime.Now.Hour; int minute = DateTime.Now.Minute; int second = DateTime.Now.Second; string status = ""; string logSize = ""; string logStatus = "The log file has not been deleted"; if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\LogFileClC.txt")) { long fileSize = new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "\\LogFileClC.txt").Length; logSize = fileSize.ToString(); if (fileSize > 10000000) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "\\archiveLogFiles"); using (Package package = ZipPackage.Open(AppDomain.CurrentDomain.BaseDirectory + "\\archiveLogFiles\\LogFileClC" + "_" + year.ToString() + month.ToString() + day.ToString() + "_" + hour + minute + second + ".zip", FileMode.Create)) { string startFolder = AppDomain.CurrentDomain.BaseDirectory; applicationLog.WriteDebugLog("Packing " + startFolder + @"\LogFileClC.txt"); Uri relUri = zipFile.GetRelativeUri(startFolder + "LogFileClC.txt"); PackagePart packagePart = package.CreatePart(relUri, System.Net.Mime.MediaTypeNames.Application.Octet, CompressionOption.Maximum); using (FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + @"\LogFileClC.txt", FileMode.Open, FileAccess.Read)) { zipFile.CopyStream(fileStream, packagePart.GetStream()); } } File.Delete(AppDomain.CurrentDomain.BaseDirectory + "\\LogFileClC.txt"); logStatus = "Log File has been deleted."; } } else if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\LogFileClC.txt")) { logStatus = "Log file not found. Created."; } return(status = "Log file size was: " + logSize + ". " + logStatus); }
private void SaveSegmentsToFile(Bitmap seg) { Size imageSize; string filename = "allImages" + counter.ToString() + "matches" + ".bmp"; if (seg.Width > segmentsToSave.Width) imageSize = new Size(seg.Width, segmentsToSave.Height + seg.Height); else imageSize = new Size(segmentsToSave.Width, segmentsToSave.Height + seg.Height); Bitmap newBitmap = new Bitmap(imageSize.Width, imageSize.Height); Graphics g; g = Graphics.FromImage(newBitmap); g.DrawImage(segmentsToSave, new Point(0, 0)); g.DrawImage(seg, new Point(0, segmentsToSave.Height)); segmentsToSave = newBitmap; segmentsToSave.Save(filename); double fileSize = new FileInfo(filename).Length; Debug.Print(fileSize.ToString()); }
public static string DecodeAsterixData(string FileName) { long Position = 0; // get total byte length of the file long TotalBytes = new System.IO.FileInfo(FileName).Length; try { // Open file for reading System.IO.FileStream FileStream = new System.IO.FileStream(FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader BinaryReader = new System.IO.BinaryReader(FileStream); while (Position < TotalBytes) { // First determine the size of the message // octet data // 0 ASTERIX CATEGORY // 1 .. 2 LENGTH OF MESSAGE BLOCK byte[] Data_Block_Buffer = BinaryReader.ReadBytes((Int32)3); int LengthOfMessageBlock = ASTERIX.ExtractLengthOfDataBlockInBytes_Int(Data_Block_Buffer); BinaryReader.BaseStream.Position = BinaryReader.BaseStream.Position - 3; // Now read the message and pass it to the parser // for decoding Data_Block_Buffer = BinaryReader.ReadBytes((Int32)LengthOfMessageBlock); ExtractAndDecodeASTERIX_CAT_DataBlock(Data_Block_Buffer, false); Position = BinaryReader.BaseStream.Position; } // close file reader FileStream.Close(); FileStream.Dispose(); BinaryReader.Close(); } catch (Exception Exception) { // Error MessageBox.Show("Exception caught in process: {0}", Exception.ToString()); } return("Read " + Position.ToString() + " of total " + TotalBytes.ToString() + " bytes"); }
private void btnAlterarImagem_Click(object sender, EventArgs e) { OpenFileDialog openFileProcurarImagem = new OpenFileDialog(); openFileProcurarImagem.Title = "Selecione uma imagem para o seu logo"; openFileProcurarImagem.InitialDirectory = @"C:\"; openFileProcurarImagem.RestoreDirectory = true; openFileProcurarImagem.Filter = "Imagens JPG (apenas formato JPG) (*.jpg)|*.jpg;"; if (!Directory.Exists(Directory.GetCurrentDirectory() + "\\IMAGENS\\")) { Directory.CreateDirectory(Directory.GetCurrentDirectory() + "\\IMAGENS\\"); } if (openFileProcurarImagem.ShowDialog() == DialogResult.OK) { Imagem img = new Imagem(); string retorno = new Imagem().gerarNovaImagem(Convert.ToInt32(tbxLargura.Text), Convert.ToInt32(tbxAltura.Text), openFileProcurarImagem.FileName.ToString(), 1, Convert.ToInt32(tbxCompressao.Text), true); tbxCaminhoImagem.Text = openFileProcurarImagem.FileName.ToString(); Image imgObj = Image.FromFile(openFileProcurarImagem.FileName.ToString()); pctImagemOrigem.Image = imgObj; pctImagemOrigem.Refresh(); long tamanhoArquivoEntrada = new System.IO.FileInfo(openFileProcurarImagem.FileName.ToString()).Length; tbxEntrada.Text = tamanhoArquivoEntrada.ToString() + " MB"; if (retorno != "ERRO")//se ele conseguir gerar ele pega o novo caminho da nova imagem { Image imgObjRet = Image.FromFile(retorno); pctImagemSaida.Image = imgObjRet; pctImagemSaida.Refresh(); tbxCaminhoSaida.Text = retorno; long tamanhoArquivoSaida = new System.IO.FileInfo(retorno).Length; tbxSaida.Text = tamanhoArquivoSaida.ToString() + " MB"; } else//senão pega a normal mesmo sem compactacao { retorno = openFileProcurarImagem.FileName.ToString(); tbxCaminhoSaida.Text = retorno; } } }
public async Task StartPlaying() { WvlLogger.Log(LogType.TraceAll, "StartPlaying()"); string filePath = GetTempFilename(); FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader binaryReader = new BinaryReader(fileStream); long totalBytes = new System.IO.FileInfo(filePath).Length; buffer = binaryReader.ReadBytes((Int32)totalBytes); fileStream.Close(); fileStream.Dispose(); binaryReader.Close(); WvlLogger.Log(LogType.TraceValues, "StartPlaying() - " + " fileStream: " + fileStream.Name + " totalBytes: " + totalBytes.ToString()); await PlayAudioTrackAsync(); }
private void button6_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = openFileDialog1.FileName; using (var md5 = MD5.Create()) { using (var stream = File.OpenRead(openFileDialog1.FileName)) { long length = new System.IO.FileInfo(openFileDialog1.FileName).Length; textBox3.Text = length.ToString(); var hash = md5.ComputeHash(stream); textBox2.Text = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant(); } } } }
public void Copy(FileInfo source, FileInfo target, int start, int stop, int size) { var inputField = new IInputField[55]; var norm = new DataNormalization {Report = this, Storage = new NormalizationStorageCSV(target.ToString())}; for (int i = 0; i < 55; i++) { inputField[i] = new InputFieldCSV(true, source.ToString(), i); norm.AddInputField(inputField[i]); IOutputField outputField = new OutputFieldDirect(inputField[i]); norm.AddOutputField(outputField); } // load only the part we actually want, i.e. training or eval var segregator2 = new IndexSampleSegregator(start, stop, size); norm.AddSegregator(segregator2); norm.Process(); }
public void Narrow(FileInfo source, FileInfo target, int field, int count) { var inputField = new IInputField[55]; var norm = new DataNormalization {Report = this, Storage = new NormalizationStorageCSV(target.ToString())}; for (int i = 0; i < 55; i++) { inputField[i] = new InputFieldCSV(true, source.ToString(), i); norm.AddInputField(inputField[i]); IOutputField outputField = new OutputFieldDirect(inputField[i]); norm.AddOutputField(outputField); } var segregator = new IntegerBalanceSegregator(inputField[field], count); norm.AddSegregator(segregator); norm.Process(); Console.WriteLine(@"Samples per tree type:"); Console.WriteLine(segregator.DumpCounts()); }
/* * Currently doesnt seek but I set it up so that every time you click the play button * it will get the song length and print it in the output. */ private int Song_Duration() { int SongLength = 0; Playlist pl = selectedHeader; Song key = currentlyPlaying; string currentDirName = @"" + key.getPath(); System.IO.FileInfo fi = null; // Completely Different from String try { fi = new System.IO.FileInfo(currentDirName); } catch { Console.WriteLine("Failed to get song Length"); } TagLib.File l = TagLib.File.Create(fi.ToString()); //create taglib file SongLength = (int)l.Properties.Duration.TotalSeconds; //get the song length in seconds return(SongLength); }
private void cboRestore_SelectedIndexChanged(object sender, EventArgs e) { if (File.Exists(((ComboItem)cboRestore.SelectedItem).Path)) { rtbRestore.Text = ""; string path = ((ComboItem)cboRestore.SelectedItem).Path; rtbRestore.Text = File.ReadAllText(path); DateTime dt = File.GetLastWriteTime(path); long length = new FileInfo(path).Length; length = length / 1024; lblDateStamp.Text = dt.ToString(); lblSize.Text = length.ToString() + " KB"; btnRestore.Enabled = true; } else { btnRestore.Enabled = false; } }
public void Init(string logFileName, StringBuilder appVersionString) { m_filePath = new FileInfo(Path.Combine(m_libraryPath.ToString(), logFileName)); //If the log file already exists then archive it if (m_filePath.Exists) { DateTime lastWriteTime = m_filePath.LastWriteTime; string modifiedTimestamp = lastWriteTime.Year.ToString() + "_" + lastWriteTime.Month.ToString() + "_" + lastWriteTime.Day.ToString() + "_" + lastWriteTime.Hour.ToString() + "_" + lastWriteTime.Minute.ToString() + "_" + lastWriteTime.Second.ToString(); string fileNameWithoutExtension = m_filePath.Name.Remove(m_filePath.Name.Length - m_filePath.Extension.Length); string newFileName = fileNameWithoutExtension + "_" + modifiedTimestamp + m_filePath.Extension; File.Move(m_filePath.ToString(), Path.Combine(m_libraryPath.ToString(), newFileName).ToString()); } int num = (int)Math.Round((DateTime.Now - DateTime.UtcNow).TotalHours); WriteLine("Log Started"); WriteLine("Timezone (local - UTC): " + num.ToString() + "h"); WriteLine("App Version: " + appVersionString); }
public AboutDialog() { InitializeComponent(); int[] versions = Core.Application.GetVersionNumbers(); Debug.Assert(versions.Length == 4); lblVersion.Text = String.Format(CultureInfo.InvariantCulture, "Version {0}.{1}.{2} - Revision {3}", versions[0], versions[1], versions[2], versions[3]); string assemblyLocation = Assembly.GetExecutingAssembly().Location; if (String.IsNullOrEmpty(assemblyLocation) == false) { DateTime buildDate = new FileInfo(assemblyLocation).LastWriteTime; // When localizing use ToLongDateString() instead. //lblDate.Text = "Built on: " + buildDate.ToLongDateString(); lblDate.Text = "Built on: " + buildDate.ToString("D", CultureInfo.InvariantCulture); } else { lblDate.Text = String.Empty; } }