Use the output(StreamReader) line as file name(rename) - c#

I am trying to use the output("line")as a new file name(files already exist, just rename).
e.g. "A,tampqer,n:.jpg"
but it looks like:
e.g. line ="A\tampqer\tn:\t\t"
I get an error: illegal character for the file name.
int counter = 0;
string line;
// Read the file and display it line by line.
StreamReader file = new StreamReader(#"C:\\german-czech.txt");
while ((line = file.ReadLine()) != null)
{
//replace /t doesnt work
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '\t')
{
line.Replace(line[i], ',');
}
}
//Console.WriteLine(string.Format(line, #"\\t").ToString());
Console.WriteLine( line);
counter++;
if (counter == 100)
break;
}
file.Close();
And guess what the content of the "line" is still the same ... can anyone help me up with this little problem ?
what else did I try ?
line.Replace(System.Environment.NewLine, ",");
string.empty...
"\n"
Best regards

You need
line = line.Replace(line[i], ',');
It doesn't change it in place. It returns a new string.
You also don't need to transverse the string one by one. Replace will replace every occurrence in the string. So instead of your:
//replace /t doesnt work
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '\t')
{
line.Replace(line[i], ',');
}
}
Just have:
line = line.Replace("\t", ',');
(This is correcting your code. But I think mrzli in his comment got the real error.)

Related

Simple way to read select lines from a file

There are 100 Lines in my .txt file. This code will read every line, Line by line. How do I change the outcome to only read line 3, line 4, and line 5 respectively?
string[] lines = System.IO.File.ReadAllLines(#"C:\Horoscope\iso_8859-1.txt");
foreach (string line in lines)
{
// Use a tab to indent each line of the file.
Console.WriteLine("\t" + line);
}
You can use System.IO.StreamReader to read the file line by line
int counter = 1;
string line;
// Read the file line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(#"C:\Horoscope\iso_8859-1.txt");
while((line = file.ReadLine()) != null)
{
if(counter > 5)
{
// No need to continue
break;
}
else if(counter >= 3)
{
System.Console.WriteLine(line);
}
counter++;
}
file.Close();

Replace text in string and save to file in .NET

I want remove a text if the program finds the text to replace, so I prepared this code:
string[] lines = File.ReadAllLines(#"pathtofile");
int Object = 0;
foreach (string line in lines)
{
if (line.Contains("Object"))
{
MessageBox.Show("contain!");
dsObject++;
}
if (Object == 1)
{
line.Replace("Object", " ");
MessageBox.Show(line);
}
File.AppendAllText(#"savefile.txt", line + Environment.NewLine);
string result = line;
// MessageBox.Show(line);
}
This does not work.
Strings are immutable in c#
therefore have to replace
line.Replace("Object", " ");
with
line = line.Replace("Object", String.Empty);
Edit
as slaven-hvar said you cannot change foreach item
therefore you to do change to "normal" for loop
for (int i = 0; i < lines.Length; i++)
{
lines[i] = lines[i].Replace("Object", String.Empty);
}
Use a for loop instead of a foreach loop because line = line.Replace("Object", String.Empty) will not compile because line is a foreach iteration variable. Instead of line = line.Replace("Object", String.Empty) use lines[i]=lines[i].Replace("Object", String.Empty); in a for loop:
string[] lines = File.ReadAllLines(#"pathtofile");
int Object = 0;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("Object"))
{
MessageBox.Show("contain!");
dsObject++;
}
if (Object == 1)
{
lines[i]=lines[i].Replace("Object", String.Empty);
MessageBox.Show(lines[i]);
}
File.AppendAllText(#"savefile.txt", lines[i] + Environment.NewLine);
string result = lines[i];
}
If you want your code to be shorter you can use this LINQ solution:
var result = lines.Select(x => x.Replace("Object", String.Empty)).ToList();
result.ForEach(line=>File.AppendAllText(#"savefile.txt", line + Environment.NewLine));

Counting the number of words from a file

A word in this context is defined is a letter or a number. However, something like \n is not considered a word.
Below in my code I am trying to count the number of words in a file but at the for loop's local variable declaration I get the error Null Reference exception.
I am not sure why I get this error. I get the variable Line equal to null which shouldn't happen because the text file DOES have one word "hello world" in it..
StreamReader sr = new StreamReader(filePath);
while (sr.ReadLine()!=null)
{
Line =sr.ReadLine();
for (**int i = 1**; i < (Line.Length+1); i++)
{
if (Char.IsLetterOrDigit(Line[i]) == true && Char.IsLetterOrDigit(Line[i - 1]) == true)
{
if (LetterRecent == false)
{
wordCount = wordCount + 1;
}
LetterRecent = true;
}
else
{
LetterRecent = false;
}
}
}
sr.Close();
You're doing ReadLine() twice for each line.
You could do something like:
count = 0;
while (line = sr.ReadLine()) {
char oldChar = 0;
for (char c in line) {
if (c != oldChar && Char.IsLetterOrDigit(c)) count++;
oldChar = c;
}
}
You are discarding half of the lines in the file by calling sr.ReadLine() twice. If you read the last line of the file in the while statement, the call to Line.Length will throw the null reference exception.
Try something this:
var wordCount = 0;
var line = sr.ReadLine();
while( line != null ) {
for( var i = 1; i < line.Length; i++ ) {
// Count words
}
line = sr.ReadLine();
}
You need to declare wordCount before using it.
Int wordCount = 0;
while (sr.ReadLine()!=null)
{
Update your loop condition to be like this:
while (sr.Peek() >= 0)
{
Line = sr.ReadLine();
}

c# search string in txt file

I want to find a string in a txt file if string compares, it should go on reading lines till another string which I'm using as parameter.
Example:
CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
I need the details to work with them otherwise.
I'm using linq to search for "CustomerEN" like this:
File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
You have to use while since foreach does not know about index. Below is an example code.
int counter = 0;
string line;
Console.Write("Input your search text: ");
var text = Console.ReadLine();
System.IO.StreamReader file =
new System.IO.StreamReader("SampleInput1.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains(text))
{
break;
}
counter++;
}
Console.WriteLine("Line number: {0}", counter);
file.Close();
Console.ReadLine();
With LINQ, you could use the SkipWhile / TakeWhile methods, like this:
var importantLines =
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.TakeWhile(line => !line.Contains("CustomerCh"));
If you whant only one first string, you can use simple for-loop.
var lines = File.ReadAllLines(pathToTextFile);
var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
if(!firstFound && lines[index].Contains("CustomerEN"))
{
firstFound = true;
}
if(firstFound && lines[index].Contains("CustomerCh"))
{
//do, what you want, and exit the loop
// return lines[index];
}
}
I worked a little bit the method that Rawling posted here to find more than one line in the same file until the end. This is what worked for me:
foreach (var line in File.ReadLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
{
current = new List<string>();
current.Add(line);
}
else if (line.Contains("CustomerEN") && current != null)
{
current.Add(line);
}
}
string s = String.Join(",", current);
MessageBox.Show(s);

c# Get array index id

Not sure if am on the right track but I want to find a index id of an array and check if it's equal to another id then display a message. it not working for some reason.
int _findID = 1;
using (StreamReader reader = new StreamReader("textfile.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
string[] array = {line};
for (int i = 0; i < array.Length; i++)
{
if (array[i] == findID)
{
MesssageBox.show("Line found!!")
}
}
}
}
Any help appreciated
try
if(int.Parse(array[i]) == findID)
instead of
if (array[i] == findID)
You have to convert your string representation of your number to a int and then compare both int's.
this is even shorter than iterating over an array which always has 1 element:
while (line != null) {
if(int.Parse(array[i]) == findID)
MesssageBox.Show("Line found!!")
}
EDIT
Try
int _findID = 1;
List<String> names = new List<string>()
using (StreamReader reader = new StreamReader("textfile.txt"))
{
string line = reader.ReadLine();
int lineCount = 0;
while (line != null)
{
lineCount++;
names.Add(line);
if (lineCount == _findID)
MessageBox.Show("Line found!!");
}
}
#user1285872: array.Length this will give array length 1 in your case when you check if (array[i] == findID) thi will be (0==findID) if the value of findID ==0 then message will show.
Your code has various problems:
First if the file is not empty you have an endless loop as you read the line once and always check the same line:
string line = reader.ReadLine();
while (line != null) {}
The array is always 1 item long as you create it in the loop itself.
But for the problem with the lineID, what exactly is the content of such a line?

Categories

Resources