I'm here to ask this question again, actually many people replied me their answers in my first question and such question was solved already. But I'm getting a new error about out of bounds exception something. Anyway, I got a new way so I got as well a new question.
How to get some strings from rich text box. Every numbers beside of the characters Q,W,X,Y,Z will be stored in my 5 labels. lbl1,2,3,4,5.
The old regex code is this:
but the error always point to the array element [2].
public void OnAddMessage(string sMessage)
{
richTextBox1.Text = richTextBox1.Text + sMessage;
using (StringReader sr = new StringReader(richTextBox1.Text))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] splitContents = regex.Split(line);
frontVal.Text = splitContents[1];
backVal.Text = splitContents[2];
leftVal.Text = splitContents[3];
rightVal.Text = splitContents[4];
tempVal.Text = splitContents[5] + "°C";
}
}
}
This might help to reproduce and solve the problem you asked.
Regex regex = new Regex("[QWXYZ]");
string lines = "Q0.01W0.02X1.23Y5.25Z38.19"
+ Environment.NewLine + "Q0.02W0.32X1.24Y5.22Z32.19";
using (StringReader sr = new StringReader(lines))
{
string line = "";
int lineCount = 0;
while ((line = sr.ReadLine()) != null)
{
lineCount++;
Console.WriteLine("Line " + lineCount.ToString());
string[] splitContents = regex.Split(line).Where(s => s != String.Empty).ToArray();
for(int i = 0; i < splitContents.Length; i++){
Console.WriteLine(splitContents[i]);
}
Console.WriteLine("");
}
}
Related
This question already has answers here:
C# Put string into TextBox
(3 answers)
Closed 6 years ago.
here is the problem: I've got two classes. Form 1 creates a .txt-File and sets two values (Strings) in it. Now I want to get these two strings by pressing a button(bDirekt), and set each string in a Textbox in Form 2.
Form 1 (should be correct as far as I know, but please tell me if I'm wrong):
public void Txfw()
{
string txBetrag = gBetrag.Text;
string txMonate = gMonate.Text;
string[] vars = new string[] { txBetrag, txMonate };
using (StreamWriter sw = new StreamWriter(#"C:\Users\p2\Desktop\variablen.txt"))
{
foreach (string s in vars)
{
sw.WriteLine(s);
}
}
}
Form 2 (got no idea how to go ahead):
private void bDirekt_Click(object sender, RoutedEventArgs e)
{
using (StreamReader sr = new StreamReader("variables.txt")) ;
string line = "";
while ((line = sr.ReadLine()) != null)
{
monate2.Text =
}
}
I really appreciate your help.
Try this
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.Append((line);
}
}
monate2.Text = sb.Tostring();
UPDATE: To separate line one with rest of the text, you can try this. There are always better ways to achieve this.
StringBuilder sb = new StringBuilder();
string headerLine = string.Empty;
int currentLine = 0;
using (StreamReader sr = new StreamReader(#"C:\Users\p2\Desktop\variablen.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
currentLine++; //increment to keep track of current line number.
if(currentLine == 1)
{
headerLine = line;
continue; //skips rest of the processing and goes to next line in while loop
}
sb.Append((line);
}
}
header.Text = headerLine;
monate2.Text = sb.ToString();
I'm back at it again with another question, this time with regards to editing text files. My home work is as follow
Write a program that reads the contents of a text file and inserts the line numbers at the beginning of each line, then rewrites the file contents.
This is what I have so far, though I am not so sure if this is the most efficient way of doing it. I've only started learning on handling text files at the moment.
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
StreamReader reader = new StreamReader(fileName);
int lineCounter = 0;
List<string> list = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
list.Add("line " + (lineCounter + 1) + ": " + line);
line = reader.ReadLine();
lineCounter++;
}
}
StreamWriter writer = new StreamWriter(fileName);
using (writer)
{
foreach (string line in list)
{
writer.WriteLine(line);
}
}
}
your help would be appreciated!
thanks once again. :]
this should be enough (in case the file is relatively small):
using System.IO;
(...)
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i< lines.Length; i++)
{
lines[i] = string.Format("{0} {1}", i + 1, lines[i]);
}
File.WriteAllLines(fileName, lines);
}
I suggest using Linq, use File.ReadLinesto read the content.
// Read all lines and apply format
var formatteLines = File
.ReadLines("filepath") // read lines
.Select((line, i) => string.Format("line {0} :{1} ", line, i+1)); // format each line.
// write formatted lines to either to the new file or override previous file.
File.WriteAllLines("outputfilepath", formatteLines);
Just one loop here. I think it will be efficient.
class Program
{
public static void Main()
{
string path = Directory.GetCurrentDirectory() + #"\MyText.txt";
StreamReader sr1 = File.OpenText(path);
string s = "";
int counter = 1;
StringBuilder sb = new StringBuilder();
while ((s = sr1.ReadLine()) != null)
{
var lineOutput = counter++ + " " + s;
Console.WriteLine(lineOutput);
sb.Append(lineOutput);
}
sr1.Close();
Console.WriteLine();
StreamWriter sw1 = File.AppendText(path);
sw1.Write(sb);
sw1.Close();
}
It is showing Null Reference Exception on line char[] myChar = read.ToCharArray();.
I am unable to figure out. Please help
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("TextFile1.txt");
string read = "";
while (read != null)
{
read = myReader.ReadLine();
Console.WriteLine(read);
}
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
{
Console.WriteLine(myChar[i]);
}
Console.WriteLine(read);
myReader.Close();
Console.ReadKey();
}
}
The read should be null when the loop is finished and calling ToCharArray on null should give exception. you can put this statement in while loop. I believe you are trying to do some experimentation as you have already printed the string with Console.WriteLine(read);
while ((read = sr.ReadLine()) != null)
{
Console.WriteLine(read);
char[] myChar = read.ToCharArray();
for (int i = 0; i < myChar.Length; i++)
Console.WriteLine(myChar[i]);
}
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
sb.Append(line);
}
}
var chars = sb.ToString().ToCharArray();
However, you should add each line into a stringbuilder and then convert it into char array. The thing is what you really want to do?
I have two csv files. In the first file i have a list of users, and in the second file i have a list of duplicate users. Im trying to remove the rows in the first file that are equal to the second file.
Heres the code i have so far:
StreamWriter sw = new StreamWriter(path3);
StreamReader sr = new StreamReader(path2);
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
string user = sr.ReadLine();
if (line != user)
{
sw.WriteLine(line);
}
File 1 example:
Modify,ABAMA3C,Allpay - Free State - HO,09072701
Modify,ABCG327,Processing Centre,09085980
File 2 Example:
Modify,ABAA323,Group HR Credit Risk & Finance
Modify,ABAB959,Channel Sales & Service,09071036
Any suggestions?
Thanks.
All you'd have to do is change the following file paths in the code below and you will get a file back (file one) without the duplicate users from file 2. This code was written with the idea in mind that you want something that is easy to understand. Sure there are other more elegant solutions, but I wanted to make it as basic as possible for you:
(Paste this in the main method of your program)
string line;
StreamReader sr = new StreamReader(#"C:\Users\J\Desktop\texts\First.txt");
StreamReader sr2 = new StreamReader(#"C:\Users\J\Desktop\texts\Second.txt");
List<String> fileOne = new List<string>();
List<String> fileTwo = new List<string>();
while (sr.Peek() >= 0)
{
line = sr.ReadLine();
if(line != "")
{
fileOne.Add(line);
}
}
sr.Close();
while (sr2.Peek() >= 0)
{
line = sr2.ReadLine();
if (line != "")
{
fileTwo.Add(line);
}
}
sr2.Close();
var t = fileOne.Except(fileTwo);
StreamWriter sw = new StreamWriter(#"C:\Users\justin\Desktop\texts\First.txt");
foreach(var z in t)
{
sw.WriteLine(z);
}
sw.Flush();
If this is not homework, but a production thing, and you can install assemblies, you'll save 3 hours of your life if you swallow your pride and use a piece of the VB library:
There are many exceptions (CR/LF between commas=legal in quotes; different types of quotes; etc.) This will handle anything excel will export/import.
Sample code to load a 'Person' class pulled from a program I used it in:
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(CSVPath)
Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
Reader.Delimiters = New String() {","}
Reader.TrimWhiteSpace = True
Reader.HasFieldsEnclosedInQuotes = True
While Not Reader.EndOfData
Try
Dim st2 As New List(Of String)
st2.addrange(Reader.ReadFields())
If iCount > 0 Then ' ignore first row = field names
Dim p As New Person
p.CSVLine = st2
p.FirstName = st2(1).Trim
If st2.Count > 2 Then
p.MiddleName = st2(2).Trim
Else
p.MiddleName = ""
End If
p.LastNameSuffix = st2(0).Trim
If st2.Count >= 5 Then
p.TestCase = st2(5).Trim
End If
If st2(3) > "" Then
p.AccountNumbersFromCase.Add(st2(3))
End If
While p.CSVLine.Count < 15
p.CSVLine.Add("")
End While
cases.Add(p)
End If
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & " is not valid and will be skipped.")
End Try
iCount += 1
End While
End Using
this to close the streams properly:
using(var sw = new StreamWriter(path3))
using(var sr = new StreamReader(path2))
{
string[] lines = File.ReadAllLines(path);
foreach (string line in lines)
{
string user = sr.ReadLine();
if (line != user)
{
sw.WriteLine(line);
}
}
}
for help on the real logic of removal or compare, answer the comment of El Ronnoco above...
You need to close the streams or utilize using clause
sw.Close();
using(StreamWriter sw = new StreamWriter(#"c:\test3.txt"))
You can use LINQ...
class Program
{
static void Main(string[] args)
{
var fullList = "TextFile1.txt".ReadAsLines();
var removeThese = "TextFile2.txt".ReadAsLines();
//Change this line if you need to change the filter results.
//Note: this assume you are wanting to remove results from the first
// list when the entire record matches. If you want to match on
// only part of the list you will need to split/parse the records
// and then filter your results.
var cleanedList = fullList.Except(removeThese);
cleanedList.WriteAsLinesTo("result.txt");
}
}
public static class Tools
{
public static IEnumerable<string> ReadAsLines(this string filename)
{
using (var reader = new StreamReader(filename))
while (!reader.EndOfStream)
yield return reader.ReadLine();
}
public static void WriteAsLinesTo(this IEnumerable<string> lines, string filename)
{
using (var writer = new StreamWriter(filename) { AutoFlush = true, })
foreach (var line in lines)
writer.WriteLine(line);
}
}
using(var sw = new StreamWriter(path3))
using(var sr = new StreamReader(path))
{
string []arrRemove = File.ReadAllLines(path2);
HashSet<string> listRemove = new HashSet<string>(arrRemove.Count);
foreach(string s in arrRemove)
{
string []sa = s.Split(',');
if( sa.Count < 2 ) continue;
listRemove.Add(sa[1].toUpperCase());
}
string line = sr.ReadLine();
while( line != null )
{
string []sa = line.Split(',');
if( sa.Count < 2 )
sw.WriteLine(line);
else if( !listRemove.contains(sa[1].toUpperCase()) )
sw.WriteLine(line);
line = sr.ReadLine();
}
}
How to start reading file from 2nd line skipping 1st line. This seems to work but is it best way to do so?
using (StreamReader sr = new StreamReader(varFile, Encoding.GetEncoding(1250))) {
string[] stringSeparator = new string[] { "\",\"" };
int i = 0;
while (!sr.EndOfStream) {
string line = sr.ReadLine(); //.Trim('"');
if (i > 0) {
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++) {
MessageBox.Show(values[index].Trim('"'));
}
}
i++;
}
}
If the file is not very large and can fit in memory:
foreach (var line in File.ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
{
string[] values = line.Split(',');
...
}
If not write an iterator:
public IEnumerable<string> ReadAllLines(string filename, Encoding encoding)
{
using (var reader = new StreamReader(filename, encoding))
{
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
}
and then consume it:
foreach (var line in ReadAllLines(varFile, Encoding.GetEncoding(1250)).Skip(1))
{
string[] values = line.Split(',');
...
}
Could you not just read the first line outside of the loop without assigning it to a variable?
using (StreamReader sr = new StreamReader(varFile, Encoding.GetEncoding(1250))) {
string[] stringSeparator = new string[] { "\",\"" };
if (!sr.EndOfStream)
sr.ReadLine();
while (!sr.EndOfStream) {
string line = sr.ReadLine(); //.Trim('"');
string[] values = line.Split(stringSeparator, StringSplitOptions.None);
for (int index = 0; index < values.Length; index++) {
MessageBox.Show(values[index].Trim('"'));
}
}
}
I'm sorry but I see no problem with the way you are doing it though. I couldn't add comment.
So just for the sake of answering, you probably could have try to call ReadLine() once before the loop. Might not be the best way as I don't know whats the behavior of running ReadLine() if its already end of stream, but it nothing is gonna happen then thats gonna save you some checks.
Updated:
To give a more complete answer, calling ReadLine() when the stream is at its end will return a null.
Reference: http://msdn.microsoft.com/en-us/library/system.io.streamreader.readline.aspx
Remember to check the return for null value.