public void Process() { // read the iris data from the resources Assembly assembly = Assembly.GetExecutingAssembly(); var res = assembly.GetManifestResourceStream("AIFH_Vol1.Resources.abalone.csv"); // did we fail to read the resouce if (res == null) { Console.WriteLine("Can't read iris data from embedded resources."); return; } // load the data var istream = new StreamReader(res); DataSet ds = DataSet.Load(istream); istream.Close(); // The following ranges are setup for the Abalone data set. If you wish to normalize other files you will // need to modify the below function calls other files. ds.EncodeOneOfN(0, 0, 1); istream.Close(); var trainingData = ds.ExtractSupervised(0, 10, 10, 1); var reg = new MultipleLinearRegression(10); var train = new TrainLeastSquares(reg, trainingData); train.Iteration(); Query(reg, trainingData); Console.WriteLine("Error: " + train.Error); }
public Mundo(FileInfo file) { FileStream fs = file.OpenRead(); StreamReader sr = new StreamReader(fs); StringReader str = new StringReader(sr.ReadToEnd()); CreateFromString(str); sr.Close(); string firstLine = sr.ReadLine(); string[] size = firstLine.Split(' '); tamX = int.Parse(size[0]) ; tamY = int.Parse(size[1]) ; celdas = new TypeCelda[tamX][]; for ( int i = 0 ; i < celdas.Length ; i++ ) { celdas[i] = new TypeCelda[tamY]; } for (int x = 0; x < tamX; x++) { for (int y = 0; y < tamY; y++) { celdas[x][y] = TypeCelda.Pasillo; } } sr.Close(); }
public static void InitSettings() { if (File.Exists (ep+"/ini.txt")) { string s; string[] st; StreamReader sr = new StreamReader (ep + "/ini.txt"); try { s = sr.ReadLine (); st = s.Split (("=") [0]); tp = st [1]; s = sr.ReadLine (); st = s.Split (("=") [0]); dp = st [1]; sr.Close (); } catch { sr.Close(); NewIni(); } } else { NewIni(); } }
public static List<double> ReadErrorsFromRecordingFile(string filename, int errorSet) { List<double> errors = new List<Double>(); StreamReader reader = new StreamReader(filename); string line; int count = 0; while ((line = reader.ReadLine()) != null) { if (line.Contains("ERRORS")) { count++; } if (count == errorSet) { line = line.Split(':')[1]; string[] error = line.Split(','); foreach (string s in error) { errors.Add(double.Parse(s.Trim())); } reader.Close(); return errors; } } reader.Close(); return errors; }
public static float[] readFromFile(string filePath) { StreamReader fileReader = null; try { fileReader = new StreamReader(filePath); } catch(Exception e) { return null; } string line = fileReader.ReadLine(); if (line == null) { fileReader.Close(); return null; } int mark = 0; string[] data = line.Split(','); if (data[data.Length - 1].Equals("")) { mark = 1; } float []dataF = new float[data.Length-mark]; for (int i = 0; i < data.Length-mark; i++) { dataF[i] = (float)Convert.ToDouble(data[i]); } fileReader.Close(); return dataF; }
public static int FileToTab(string filename, ref int[,] tab) { int j = 0; StreamReader SR; string line = ""; Sudoku.InitTab (tab); try { SR = new StreamReader (filename); } catch (Exception) { Console.WriteLine ("ERROR : File does not exist !"); return 1; } while ((line = SR.ReadLine()) != null && j < tab.GetLength(1)) { if (line.Length < tab.GetLength (0)) { Console.WriteLine ("ERROR : Bad file format, not enough character for the Sudoku."); Console.WriteLine ("Need at least {0} !", tab.GetLength (0)); SR.Close (); return 2; } for (int i = 0; i < tab.GetLength(0); ++i) tab [i, j] = Convert.ToInt32 (line [i].ToString ()); ++j; } SR.Close (); return 0; }
private static int UsersCurrentLevel(string username) { try { StreamReader reader = new StreamReader("UserInformation.txt"); string line = ""; while (line != null) { line = reader.ReadLine(); if (line != null) { string[] userInformation = line.Split('/'); if (userInformation[0] == username) { reader.Close(); return int.Parse(userInformation[2]); } } } reader.Close(); return -1; } catch (Exception ex) { MessageBox.Show("Error reading from text file: " + ex.Message, "Important", MessageBoxButtons.OK, MessageBoxIcon.Information); return -1; } }
public static void ParseMapFile(string file, ref Dictionary<string, string> map) { //openfile string line; int count = 0; System.IO.StreamReader filereader = new System.IO.StreamReader(file); //read line by line while ((line = filereader.ReadLine()) != null) { count++; Console.WriteLine(line); //debug line = line.Trim(); if (line.StartsWith("#") || line.Equals("")) continue; string[] methods = line.Split(';'); if (methods.Length != 2) { filereader.Close(); throw new InvalidFileFormatException("more/less than one splitter is detected on line "+count.ToString()); } string keystr = methods[0].Trim(); string valstr = methods[1].Trim(); map[keystr] = valstr; } filereader.Close(); //string keystr = "System.Windows.Forms.MessageBox::Show"; //string valstr = "System.Console::Writeline"; //map[keystr] = valstr; }
public static ProxySettingsDTO GetProxySettings() { ProxySettingsDTO proxySettings = new ProxySettingsDTO(); StreamReader reader = null; try { reader = new StreamReader(".\\netconxsettings.xml"); XmlSerializer xSerializer = new XmlSerializer(typeof(ProxySettingsDTO)); proxySettings = (ProxySettingsDTO)xSerializer.Deserialize(reader); reader.Close(); } catch { if(reader != null) reader.Close(); TextWriter writer = new StreamWriter(".\\netconxsettings.xml"); try { XmlSerializer serializer = new XmlSerializer(typeof(ProxySettingsDTO)); serializer.Serialize(writer, proxySettings); } finally { writer.Close(); } } return proxySettings; }
public string ReadLRCFile(string filePath) { Stream stream = null; StreamReader reader = null; string str = ""; string strInput = ""; try { stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); reader = new StreamReader(stream, Encoding.GetEncoding("gb2312")); this.LrcList.Clear(); while (!reader.EndOfStream) { strInput = reader.ReadLine() + "\r\n"; str = str + this.regLrc(strInput); } reader.Close(); stream.Close(); } catch { reader.Close(); stream.Close(); } return str; }
public static string HttpRequestByGet(string Url, CookieContainer cookieContainer) { HttpWebRequest webRequest = null; WebResponse webResponse = null; StreamReader sr = null; string response = ""; try { webRequest = (HttpWebRequest)WebRequest.Create(Url); if (cookieContainer != null) { webRequest.CookieContainer = cookieContainer; } webResponse = webRequest.GetResponse(); sr = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("UTF-8")); response = sr.ReadToEnd(); sr.Close(); sr = null; } catch { } finally { if (webResponse != null) { webResponse.Close(); ; } if (sr != null) { sr.Close(); sr = null; } } return response; }
public void GetResourcesPath() { // read resourcesPath if(!File.Exists(Application.StartupPath + "\\" + prefsFileName)) { File.Create(prefsFileName).Close(); // create the file, and immediately release it } StreamReader reader = new StreamReader(Application.StartupPath + "\\" + prefsFileName); if((resourcesPath = reader.ReadLine()) == null || !(new DirectoryInfo(resourcesPath).Exists)) { FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.SelectedPath = Application.StartupPath; dlg.Description = "Please locate the 'Resources' directory (about 3 levels up from the debug directory) :"; if(dlg.ShowDialog() == DialogResult.Cancel) Application.Exit(); resourcesPath = dlg.SelectedPath; reader.Close(); StreamWriter output = new StreamWriter(Application.StartupPath + "\\" + prefsFileName); output.WriteLine(resourcesPath); output.Close(); } else { reader.Close(); } }
protected void LoadContentTemplates() { DirectoryInfo di = new DirectoryInfo(ContentTemplateManager.TemplatesPath); foreach (FileInfo fi in di.GetFiles("*.ctpl")) { ContentTemplate template = new ContentTemplate(); using (StreamReader sr = new StreamReader(fi.OpenRead())) { if (sr.ReadLine() != "ContentTemplate") { sr.Close(); return; } template.Name = sr.ReadLine(); template.Shortcut = sr.ReadLine(); template.Mode = (ContentTemplateMode)Enum.Parse(typeof(ContentTemplateMode), sr.ReadLine()); template.Content = sr.ReadToEnd(); ContentTemplateManager.Manager.Add(template); sr.Close(); } } }
public static void load(string fileName, Graph graph) { StreamReader reader = null; try { reader = new StreamReader(File.Open(fileName, FileMode.Open)); String line = ""; while ((line = reader.ReadLine()) != null) { graph.add(Edge.parse(graph, line)); } reader.Close(); } catch (Exception e) { throw new BadFileFormatException("Unexpected error while parsing '" + fileName + "'.", e); } finally { if (reader != null) { reader.Close(); } } }
public static string SerializeToText(System.Type ObjectType, Object Object) { string RetVal; StreamWriter Writer; StreamReader Reader; MemoryStream Stream; RetVal = string.Empty; Stream = new MemoryStream(); Reader = new StreamReader(Stream); Writer = new StreamWriter(Stream); try { if (Object != null && ObjectType != null) { Serialize(Writer, ObjectType, Object); Stream.Position = 0; RetVal = Reader.ReadToEnd(); Writer.Flush(); Writer.Close(); Reader.Close(); } } catch (Exception ex) { Writer.Flush(); Writer.Close(); Reader.Close(); throw ex; } return RetVal; }
public static Object LoadFromText(System.Type ObjectType, string XmlContent) { Object RetVal; MemoryStream Stream; StreamReader Reader; StreamWriter Writer; RetVal = null; Stream = new MemoryStream(); Reader = new StreamReader(Stream); Writer = new StreamWriter(Stream); try { if (!string.IsNullOrEmpty(XmlContent)) { Writer.Write(XmlContent); Writer.Flush(); Stream.Position = 0; RetVal = Deserialize(Reader, ObjectType); Writer.Close(); Reader.Close(); } } catch (Exception ex) { Writer.Close(); Reader.Close(); throw ex; } return RetVal; }
/// <summary> /// Reads the configuration file, catches all errors and returns a null user /// </summary> /// <returns>The user which read out the file. Occuring error returning a null Object.</returns> internal User ReadUserCfgFile() { try { using (StreamReader sr = new StreamReader("user.cfg")) { // Read the stream to a string, and write the string to the console. String line = sr.ReadToEnd(); if (line.Length > 0) { String[] split = line.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); long id = long.Parse(split[1]); User user = new User(split[0]); user.Id = id; sr.Close(); return user; } sr.Close(); } } catch (FileNotFoundException ex) { Logger.LogException("File could not be found by the application.", ex); } catch (IOException ex) { Logger.LogException("File could not be read by the application.", ex); } catch (Exception ex) { Logger.LogException("File could not be read by the application.", ex); } return null; }
/// <summary> /// ���ļ� /// </summary> /// <param name="filename"></param> /// <returns></returns> private static string getFileData(string filename) { StreamReader reader = null; string data = string.Empty; try { reader = new StreamReader(filename, System.Text.Encoding.GetEncoding("gb2312")); data = reader.ReadToEnd(); reader.Close(); return data; } catch (IOException e) { nSearch.DebugShow.ClassDebugShow.WriteLineF(e.Message); } finally { if (reader != null) reader.Close(); } return ""; }
bool ParseZR(char letter, out string result) { StreamReader srConfig = new StreamReader("Confige.tap"); string line = ""; result = ""; bool found = false; while (!srConfig.EndOfStream) { line = srConfig.ReadLine(); if (!string.IsNullOrEmpty(line) && line[0] == letter) { found = true; break; } } if (found) line = line.Substring(2); else { MessageBox.Show(string.Format("Не найден:{0}{1}Процесс не был закончен", letter, System.Environment.NewLine)); srConfig.Close(); return false; } result = line; srConfig.Close(); return true; }
public FloodUC(AccountUC account) { InitializeComponent(); m_Account = account; string pathPlayers = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "BlueSheep", "Accounts", m_Account.AccountName, "Flood"); if (!Directory.Exists(pathPlayers)) Directory.CreateDirectory(pathPlayers); PrivateExitBox.Hide(); FloodContent = ""; Dictionary<string, int> temp = new Dictionary<string, int>(); if (File.Exists(pathPlayers + @"\Players.txt")) { var sr = new StreamReader(pathPlayers + @"\Players.txt"); while (!sr.EndOfStream) { string line = sr.ReadLine(); string[] parsed = line.Split(','); if (parsed.Length > 1) { temp.Add(parsed[0], int.Parse(parsed[1])); PlayerListLb.Items.Add(line); } else { sr.Close(); File.Delete(pathPlayers + @"\Players.txt"); return; } } sr.Close(); m_Account.Log(new DebugTextInformation("[ADVANCED FLOOD] Players loaded."), 5); } }
public bool ImportInputParameter(string InputPath) { TextReader reader = new StreamReader(InputPath); try { XmlSerializer deserializer = new XmlSerializer(typeof(AMLParameterObject)); object obj = deserializer.Deserialize(reader); var amlObj = (AMLParameterObject)obj; this.Url = amlObj.Url; this.APIKey = amlObj.APIKey; this.Title = amlObj.Title; this.Description = amlObj.Description; this.Copyright = amlObj.Copyright; this.listInputParameter = amlObj.listInputParameter; this.listOutputParameter = amlObj.listOutputParameter; reader.Close(); return true; } catch (Exception) { reader.Close(); return false; } }
public static void Clean() { string[] files = Directory.GetFiles(@"c:\windows\inf\", "*.inf",SearchOption.AllDirectories); foreach (string file in files) { using (StreamReader sr = new StreamReader(File.OpenRead(file))) { // USB\VID_26AC 3dr // USB\VID_2341 arduino while (sr.BaseStream != null && !sr.EndOfStream) { string line = sr.ReadLine(); if (line.ToUpper().Contains(@"USB\VID_26AC") || line.ToUpper().Contains(@"USB\VID_2341")) { try { Console.WriteLine(file); sr.Close(); File.Delete(file); } catch { } //System.Diagnostics.Process.Start("PnPutil.exe");//, "-f -d " + Path.GetFileName(file)); } } sr.Close(); } } }
// Читаем опеределенный параметр из файла, получаем значение. public static string GetProperty(string propertyName) { string propertyValue = ""; if (CheckFile()) { StreamReader sreader = new StreamReader(_filePath); string line; while ((line = sreader.ReadLine()) != null) { line = TransformLine(line); if (line == "") continue; if (line.Substring(0, line.IndexOf('=')) == propertyName) { propertyValue = line.Substring(line.IndexOf('=') + 1, line.Length - line.IndexOf('=') - 1); sreader.Close(); return propertyValue; } } Console.WriteLine("Свойство '{0}' не найдено в файле.", propertyName); sreader.Close(); return ""; } else return ""; }
public static List<string> carregaLista(string pArquivo) { List<string> lista = new List<string>(); if (!File.Exists(pArquivo)) { StreamWriter w = File.CreateText(pArquivo); w.Close(); } string texto; StreamReader sRarquivo = new StreamReader(pArquivo); try { while ((texto = sRarquivo.ReadLine()) != null) { lista.Add(texto); } sRarquivo.Close(); } catch (Exception erro) { sRarquivo.Close(); Erro.Show(erro); utilitario.salvaErros(erro, utilitario.caminhoEXE() + @"\erro.log"); } return lista; }
public static T_SeamateItems ParseItemsConfiguration(String configPath) { TextReader tr = null; XmlTextReader xml = null; XmlValidatingReader validate = null; xml = new XmlTextReader(configPath); validate = new XmlValidatingReader(xml); validate.ValidationEventHandler += new ValidationEventHandler(xsdValidationHandler); while (validate.Read()) { } validate.Close(); try { tr = new StreamReader(configPath); XmlSerializer serializer = new XmlSerializer(typeof(T_SeamateItems)); T_SeamateItems config = (T_SeamateItems)serializer.Deserialize(tr); tr.Close(); return config; } catch (Exception ex) { if (tr != null) { tr.Close(); } throw new Exception("Unable to read configuration file: " + configPath, ex); } return null; }
static void ReplaceTextInFiles(ref string stringToFind, ref List<string> listFilesWithFindedString) { Console.WriteLine($"Искомое значение {stringToFind} было найдено в таких файлах:"); foreach (var lst in listFilesWithFindedString) { Console.WriteLine(lst); } Console.WriteLine($"Введите текст на который Вы хотите заменить {stringToFind}:"); string replaceText = Console.ReadLine(); foreach (var fileList in listFilesWithFindedString) { StreamReader fileReader = new StreamReader(fileList); string content = fileReader.ReadToEnd(); fileReader.Close(); content = Regex.Replace(content, stringToFind, replaceText); StreamWriter writer = new StreamWriter(fileList); writer.Write(content); writer.Close(); fileReader.Close(); } }
///<summary> /// /// Método que verifica a existência do cadastro do login e hash passados no arquivo de log /// local retornando verdadeiro caso exista /// ///</summary> public static bool verificaCadastroUsuarioLocal(string login, string hash) { try { StreamReader le = new StreamReader(CAM_LOG); string chave; while ((chave = le.ReadLine()) != null) { if (chave == login + " " + hash) { le.Close(); return true; } } le.Close(); return false; } catch (DirectoryNotFoundException except) { throw new excecao.excecao(ERRO); } }
/// <summary>Read and eval all the lines in a file</summary> internal static void Do(string file, IScope scope) { StreamReader stream = null; try { List<string> lines = new List<string>(); stream = new StreamReader(file); while (!stream.EndOfStream) lines.Add(stream.ReadLine()); LineConsumer consumer = new LineConsumer(lines); EvalLines.Do(consumer, scope); stream.Close(); } catch (Loki3Exception e) { e.AddFileName(file); if (stream != null) stream.Close(); throw e; } catch (System.Exception e) { if (stream != null) stream.Close(); throw e; } }
protected bool isUsernameAlreadyExists(string userName) { try { StreamReader reader = new StreamReader("UserInformation.txt"); string line = ""; while (line != null) { line = reader.ReadLine(); if (line != null) { string[] userInformation = line.Split('/'); if (userInformation[0] == userName) { reader.Close(); return true; } } } reader.Close(); return false; } catch (Exception ex) { MessageBox.Show("Error reading from text file: " + ex.Message, "Important", MessageBoxButtons.OK, MessageBoxIcon.Information); return false; } }
private String ReadFile(String filename) { StreamReader read = null; if (System.IO.File.Exists(filename) == false) { WriteFile(filename, "0"); return "0"; } else { try { read = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)); String outValue = read.ReadLine().Trim(); read.Close(); return outValue; } catch (Exception e) { } finally { read.Close(); } return "0"; } }