My code to write text to a file works perfectly...
string path = #"./prefs.dat";
string stringdir = textBox1.Text + Environment.NewLine + textBox2.Text + Environment.NewLine;
System.IO.File.WriteAllText(path, stringdir);
Then to read from the file I use this code which again works perfectly...
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
string s = lines[0];
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
However when I want to read the 2nd line using the exact same code except changing...
string s = lines[1];
Then it fails, I get a null result. When I look into further the error doesn't even see the 2nd line even though I clearly have two lines.
ReadLine() method reads one line at a time,you need to add all lines by using a while loop following way:
string line="";
while((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
string s = lines[1];
See this MSDN article (Reading a Text File One Line at a Time) for more details
The other way around can be to read all lines at once using ReadAllLines() and then access second line:
string[] lines = System.IO.File.ReadAllLines(stringdir);
string s = lines[1];
See this MSDN article on How to: Read From a Text File
You can also read all lines altogether
string[] lines = System.IO.File.ReadAllLines("path");
If you want to get content of second line as string s = lines[1]; you need to add that to the list first
Process test = new Process();
string FileName = "prefs.dat";
StreamReader sr = new StreamReader(FileName);
List<string> lines = new List<string>();
lines.Add(sr.ReadLine());
lines.Add(sr.ReadLine());
string s1 = lines[0];
string s2 = lines[1]; // Now you can access second line
sr.Close();
test.StartInfo.FileName = s;
test.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
test.StartInfo.CreateNoWindow = false;
test.Start();
Related
I Have one text file and I want to replaces all matches in each line, so I defined Pattern and I loop through to the text file after I want to write the result in another file, unfortunately my pattern is only replace first occurrence of the word what did |I do in a wrong way?
Content of text file:
"testebook kok o testebook\ntestbbb1232 joj ds testbbb1232"
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
string ma = #"^test[0-9a-zA-Z]+";
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, "");
}
newString += line + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
Your code is correct but your regex pattern is not correct.
you should write this:
string ma = #"test[0-9a-zA-Z]+";
The letter "^" has removed from pattern
So I modified My pattern and remove start with character and everything works now as desired
using System.Text.RegularExpressions;
string filePath = "test.txt";
string fileNewPath = "test1.txt";
MatchesFinder test = new(filePath, fileNewPath);
test.RunTheProcess();
class MatchesFinder{
private string filePath;
private string fileNewPath;
private string ma = #"test[a-zA-Z0-9]+";
public MatchesFinder(string filePath,string fileNewPath){
this.filePath = filePath;
this.fileNewPath = fileNewPath;
}
public void RunTheProcess(){
string newString = string.Empty;
using(StreamReader sr = new(filePath)){
string line = sr.ReadLine();
while (line != null){
while(Regex.IsMatch(line, ma) != false){
line = Regex.Replace(line, ma, string.Empty);
}
newString += line.TrimStart() + "\n";
line = sr.ReadLine();
}
}
using(StreamWriter sw = new(fileNewPath)){
sw.WriteLine(newString);
}
}
}
I think you don´t need to check IsMatch separately, just calling Regex.Replace should yield the same result.
Also, newString += line.TrimStart() + "\n"; means you´re copying all the lines you´ve already checked every time you append a new line. I´d either write directly to the output stream or at least use a StringBuilder if you really want to have the full file in memory for some reason.
Something like this:
using var sw = new StreamWriter(fileNewPath);
using var sr = new StreamReader(filePath);
var line = sr.ReadLine();
while (line != null){
line = Regex.Replace(line, ma, string.Empty);
sw.WriteLine(line.TrimStart());
line = sr.ReadLine();
}
I am trying to read a text file line by line inside a textbox, but it returns only the word "!MANAGERS" in the textbox.
My text file is:
!MANAGERS
NUMBERS = 6
ADMIN = 1
!INFORMATIONS
741852:PAULO MARCO:MANAGER:TEAM
My code to get the file is:
public static string GetFile () {
string filepath = #"C:\Files\projectmanager.txt";
StreamReader reader = new StreamReader (filepath);
string lines = reader.ReadLine ();
var list = new List<string> ();
list.Add (lines);
string[] liness = list.ToArray ();
foreach (string line in liness) {
return line;
}
return "ERROR";
}
My textbox code is:
String filetext = ToolLibrary.FileSystem.GetFile();
textbox1.Text = filetext;
If this is an option for you, this can be done in one line provided you have set Multiline to true on your textbox properties.
textbox1.Lines = System.IO.File.ReadAllLines(#"C:\Files\projectmanager.txt");
You can simply write
textbox1.Text = File.ReadAllText(filepath);
Also, set the Multiline property of the text box to true. (You can do so in the properties window.)
I have seen many examples that show StreamReader taking the arugment "Properties.Resources.someTextFile, and apparently they work great. However, in .net 4.5 I still get:
//while not end of file, read lines of file and split into array
string myFile = Properties.Resources.data;
string line;
StreamReader reader = new StreamReader(myFile);
while ((line = reader.ReadLine()) != null)
{
string[] array = line.Split('#');
string tickerSymbol = array[0];
string regPattern = array[1];
....
So, what am I doing wrong?
By accessing the data text file resource through Properties.Resources the resulting variable myFile should contain the string contents of the file.
string myFile = Properties.Resources.data;
var lines = myFile.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach(var line in lines)
{
// Process each line...
}
I'm trying to remove any "new line" characters from each line of text in my log file.
Below is an example entry that I am reading in with a Stream Reader :-
<![LOG[Raising event:
[SMS_CodePage(850), SMS_LocaleID(2057)]
instance of SoftDistProgramStartedEvent
{
AdvertisementId = "000216F6";
ClientID = "GUID:B55C2757-CBAE-468E-B54F-46CAF2ECF68F";
CommandLine = "\"C:\\WINNT\\system32\\cscript.exe\" /nologo Shutdown_Desktops_Overnight.vbs";
DateTime = "20130211080211.784000+000";
MachineName = "DWD*****";
PackageName = "0000073C";
ProcessID = 2516;
ProgramName = "Shutdown Desktops Overnight";
SiteCode = "S00";
ThreadID = 3640;
UserContext = "NT AUTHORITY\\SYSTEM";
WorkingDirectory = "C:\\WINNT\\system32\\CCM\\Cache\\0000073C.1.System\\";
};
]LOG]!><time="08:02:11.800+000" date="02-11-2013" component="execmgr" context="" type="1" thread="3640" file="event.cpp:522">
In the actual Logfile this is displayed as one line in the file, with the "New Line Characters" replaced with a square.
I'm using the following code to read in the log entries :-
using (StreamReader sr = new StreamReader(#"C:\Documents and Settings\riversd\Desktop\Logfile2.log"))
{
string Line;
while ((Line = sr.ReadLine()) != null)
{
}
}
The issue is that when the StreamReader reads this entry from the txt file it breaks at :-
"<![LOG[Raising event:"
I need to remove all new line characters in this entry, on the fly. I don't want to read the entire file into memory and then remove them, I'd rather deal with each log as I read it.
Is it possible?
The call to Replace isn't working because of this detail from the MSDN doc of StreamReader.ReadLine:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.
So if you're going to use StreamReader.ReadLine to read in the input, you could build up a new string with StringBuilder.Append (not AppendLine) as StreamReader.ReadLine implicitly removes the new line characters.
var filePath = "text.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader reader = new StreamReader(filePath))
{
while (!reader.EndOfStream)
{
sb.Append(reader.ReadLine());
}
}
File.WriteAllText(filePath, sb.ToString());
sr.ReadLine().Replace(Environment.NewLine, String.Empty);
EDIT:
In case the end of line is not \r\n but \n you can use regex:
Line = Regex.Replace(sr.ReadLine(), #"(\r\n|\n)", String.Empty);
i dont know if anyone else was having exactly this issue.
here is the code i used to fix this issue.
using (System.IO.FileStream File = new System.IO.FileStream(e.FullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (System.IO.StreamReader Reader = new System.IO.StreamReader(File, Encoding.Default))
{
String CompleteData = Reader.ReadToEnd();
foreach (String Line in CompleteData.Split(new char[] { (char)13 }, StringSplitOptions.RemoveEmptyEntries))
{
if (Line.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)[0].Contains("Raising event"))
{
//Do Stuff
}
}
Reader.Close();
}
File.Close();
}
For some reason i had to do this because just using streamreader would throw an exception saying that the file is in use from another process.
It might help someone else at a later date..
I am making a project that uses streamreader and streamwriter, Is it possible that I only replace or save a text in an specific line only without affecting the other lines?
if I make like this
streamreader sr = new streamreader(#"txtfile");
list<string> lines = new list<string>();
while (!sr.EndOfStream)
sr.readline();
{
lines.Add(sr.ReadLine();
}
//put in textbox
sr.close();
{
streamwriter sw = new streamwriter(#"txtfile");
sw.WriteLine(textBox1.text);
sw.close();
}
this is just a sample, but Is it possible that I use list also un streamwriter?
If you want a one line solution (code golf :) ) you can use
string path = #"C:\Test.txt";
string lineToReplace = "Relpace This Line";
string newLineValue = "I Replaced This Line";
File.WriteAllLines(path, File.ReadAllLines(path).Select(line => line.Equals(lineToReplace) ? newLineValue : line));
You cannot just change a line as such but you can to ReadAllLines, find the line you want to change, change it and write all of it to the file again :
StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(#"txtfile");
foreach (string line in file)
{
if (line.Contains("string you want to replace"))
{
temp = line.Replace("string you want to replace", "New String");
newFile.Append(temp + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
File.WriteAllText(#"txtfile", newFile.ToString());
Read the file into memory, changing the line(s) you want to change, close the reader, open the file for writing, write the new contents of the file out.