C# how to append text in end of row text file? - c#

i have text file like this
IPen ID,Datetime,Status,Data Received
is it possible to add some word in end of row. I want append some word so the final result is :
IPen ID,Datetime,Status,Data Received,Data Reply
i already browsing and searching, the result only show append text in new line, but thats not what i want, i want append text in end of row. any suggestion for me?

It's not overly clear what you're asking, but it sounds like you're saying that any line in a file that has the text "IPen ID,Datetime,Status,Data Received" should be replaced with the text "IPen ID,Datetime,Status,Data Received,Data Reply".
If that's the case then this code works:
File
.WriteAllLines(#"path",
File
.ReadAllLines(#"path")
.Select(x =>
x + (x == "IPen ID,Datetime,Status,Data Received" ? ",Data Reply" : "")));

You can add text at the end of an existing file like this:
using (var stream = new StreamWriter("Your file path here"))
{
stream.Write("Your text here");
}
This method will add the text in a new line only if there is already a end of line character on the end of file. Otherwise, it will add on the same line.
This also adds the text only on the end of the file, if you need to select the line or insert into all lines that match a specific condition it will be a little more complicated, but I can show you if you tell me exactly what you need.
EDIT: Since you need to add the text in the middle of a line, we should read all the lines, change then and save them back on the file:
// Define your file path.
var filePath = "Your file path here";
// Fill an array with the lines from the txt file.
var txtLines = File.ReadAllLines(filePath);
// Change all lines into what you want.
var changedLines = ChangeLines(txtLines);
// Write the file with all the changed lines.
File.WriteAllLines(filePath, changedLines);
And this is how to change the lines:
public static IEnumerable<string> ChangeLines(IEnumerable<string> lines)
{
foreach (var line in lines)
{
yield return line.Replace("A C", "A B C");
}
}
This will replace all the occurrences of "A C" with "A B C". If you want to add something after some text, before, split a line in two or whatever you want, you can change this method to do what you want and all the changes will be saved back into the file. I hope that helps.

Related

C# How to duplicate line in text file (.txt) when button is clicked?

I've a winform application and I want to ducplicate a line in a text file (.txt) when I click a button.
eg :
Hello world
and I want to have something like:
Hello world
Hello world
when I click a button.
void duplicateLine(string text, int line){
//Read text file
//duplicate the line
//insert (Write) the duplicate line in text file(.txt)
}
One way to duplicate a line in a text file in C# is to use the File.ReadAllLines method to read the file into a string array, then use a loop to insert the duplicate line at the desired index, and then use the File.WriteAllLines method to write the modified array back to the file. For example, the following code snippet duplicates the first line of a text file:
void duplicateLine(string text, int line)
{
//Read the file into a string array
string[] lines = File.ReadAllLines("textfile.txt");
//Create a list to store the modified lines
List<string> newLines = new List<string>();
//Loop through the array and insert the duplicate line
for (int i = 0; i < lines.Length; i++)
{
//Add the original line to the list
newLines.Add(lines[i]);
//If the line is the one to be duplicated, add it again
if (i == line)
{
newLines.Add(lines[i]);
}
}
//Write the modified list back to the file
File.WriteAllLines("textfile.txt", newLines);
}
This code will result in a text file like this:
Hello world
Hello world
Some other line
Another line
It is better to write the code yourself and ask questions about the code problems. Try the following method:
1-Read all line of file to list using File.ReadAllLines
2- check line if not exist in the file
3-Add a new line at a specific position of list( duplicate one line)
4-Write list to file
void duplicateLine(string text, int line){
string _path = "data.txt"; //path of your file
var txtLines = File.ReadAllLines(_path).ToList(); //1
if(line>=txtLines.Count) //2
{
MessageBox.Show("this line not exist in file..");
return;
}
txtLines.Insert(line, Text); //3
File.WriteAllLines(_path, txtLines); //4
}

c# File.ReadAllLines doesn't read blank lines

I am using c# for reading some txt documents and writing/deleting some lines in them
I have to read a text document, delete some of it's lines and then save it again in the same path.
It worked all good until I realized that it doesn't read empty lines or when there is just a space in a new line :(.
Here's my text file structure:
-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
****here comes the empty line****
Here's my code:
List<string> myLines = File.ReadAllLines(path).ToList();
if (myLines.Count > 5)
{
for(int i = 7; i >= 5; i--)
{
myLines.RemoveAt(i);
}
File.WriteAllLines(path, myLines.ToArray());
}
So I don't know why when I run File.ReadAllLines will give me 7 lines (ignoring the blank one) and of course after I delete something in the file, the blank line is still there.
Note: I am working with more than 100k files, either way I would just delete that specific line by hand.
Can you help me sort this out and delete that blank line? Thank you.
Here's some code:
var f = #"-Name
-LastName
-Age
-Phone
-Address
-Address2(optional) -// this line will be deleted
-Address3(optional) -// this line will be deleted
-Name2";
File.WriteAllText(#"C:\temp\a.txt", f);
var f2 = File.ReadAllLines(#"C:\temp\a.txt").ToList();
f2.RemoveAt(7);
f2.RemoveAt(6);
f2.RemoveAt(5);
File.WriteAllLines(#"C:\temp\b.txt", f2);
Open the two resulting files a.txt and b.txt in c:\temp (make sure you have a c:\temp) - the a has blank lines, the b has no interim blank lines or address2/3
..but do note that b has a blank line at the end, because File.WriteAllLines will end the final line (Name2 in my example) with a CRLF.
If this is what you're talking about/you don't want, consider something else instead, perhaps:
File.WriteAllText(#"C:\temp\b.txt", string.Join(Environment.NewLine, f2));

How to add text to the line that starts with "hello" in a file

I have a file that contains many lines. There is a line here looking like below:
hello jim jack nina richi sam
I need to add a specific text salmon in this line and change it to below (it could be added anywhere in this line -end -begining - in the middle -doesnt matter ):
hello jim jack nina richi sam salmon
I tried:
string path = #"C:\testFolder\newTestLog.txt";
StreamReader myReader = new StreamReader(path);
string[] allLines = File.ReadAllLines(path);
foreach (string element in allLines) {
if (element.StartsWith("hello"))
{
Console.WriteLine(element);
}
}
myReader.Close();
}
Using this I'm able to read the file line by line and add each line to an array and print that line if that starts with "hello", but I'm not sure how to add text to this line
You should use what Joel answered it's nicer but if you're having trouble implementing it try this. After adding the salmon to the lines that start with hello you can overwrite the txt file by using File.WriteAllLines
string filePath = #"C:\testFolder\newTestLog.txt";
string[] allLines = File.ReadAllLines(filePath);
for(int i = 0; i < allLines.Length; i++)
{
if (allLines[i].StartsWith("hello"))
{
allLines[i] += " salmon";
}
}
File.WriteAllLines(filePath, allLines);
Try this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
foreach (string line in lines)
Console.WriteLine(line);
Note that this still only writes the results to the Console, as your sample does. It's not clear what you really want to happen with the output.
If you want this saved to the original file, you've opened up a small can of worms. Think of all of the data in your file as if it's stored in one contiguous block1. If you append text to any line in the file, that text has nowhere to go but to overwrite the beginning of the next. As a practical matter, if you need to modify file, this often means either writing out a whole new file, and then deleting/renaming when done, or alternatively keeping the whole file in memory and writing it all from start to finish.
Using the 2nd approach, where we keep everything in memory, you can do this:
string path = #"C:\testFolder\newTestLog.txt";
var lines = File.ReadAllLines(path).Select(l => l + l.StartsWith("hello")?" salmon":"");
File.WriteAllLines(path, lines);
1 In fact, a file may be split into several fragments on the disk, but even so, each fragment is presented to your program as part of a single whole.

Reading txt file checking for control characters

I have a text file that I need to parse. I need to be able to check the result of a line if it has char(28)char(13)...when read lines via below it strips out the control characters and gives me an empty string...Is there a better way to search for control charcters in a file?
var _endMessage = string.Format("{0}{1}", Convert.ToChar(28).ToString(), Convert.ToChar(13).ToString());
foreach (string line in File.ReadLines(_logFile.FullName))
{
if (Regex.Match(line, _endMessage)
{
// Do something here
}
}
Thanks

How to read a particular field from comma separated text file line using c#

I saw many post here but all are telling about how to read a text file line by line..
but i dont want line by line, i want to read a line field by field.
Example of my text file is following
Accepted, 2013/02/22, 20:12, ss123, 1234,1234,1234,Failed*Some reason ,20,500
Rejected, 2013/02/22, 20:12, ss123, 1234,1234,1234,Failed*Some reason ,20,500
output text file i want like:
Accepted, 2013/02/22, 20:12, ss123, 1234,1234,1234,Accepted,20,500
Rejected, 2013/02/22, 20:12, ss123, 1234,1234,1234,Some reason ,20,500
in the above out put example, first i need to check if the line contains Accepted or not, if it contains Accepted then i need to replace 8th column(Failed*Some reason) with Accepted otherwise i need write only reason in 8th column(Some reason) why it is Rejected..
thanks in advance if u could solve my problem...
I am thinking do like following code..anybuddy plz help me..
enter code here
try
{
System.IO.TextReader ReadFile = new StreamReader("c:\\ATMLOG.txt");
System.IO.TextWriter writeFile = new StreamWriter("c:\\DeatailReport.txt");
string line = ReadFile.ReadLine()
while(line!=null)
{
if(line.contains("Accepted")
{
string[] strArr = line.Split(',');
strArr[8]="Accepted";//i wanted to replace 8th column of comma separated text file line with Accepted
TextWrite.writeln(line);
}
else
{
switch(strArr[8])
{
case "some reasson" : //which reason will be mached that should be write on 8th column of comma separated text file
case "some reasson":
;
;
;
}
}
catch (IOException ex)
{
MessageBox.Show(ex.ToString());
}
you can get an array of fields with String.Split()
string[] strArr = myStr.Split(',');
I wouldn't even bother with performing the split. Since it appears everything is Failed*Some Reason and you simply need Failed* to disappear, I'd perform a replace:
line = line.Replace("Failed*", "");
To make it slightly more efficient you could still check for Accepted.
if (!line.Contains("Accepted"))
{
line = line.Replace("Failed*", "");
}

Categories

Resources