Reading txt file checking for control characters - c#

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

Related

Can someone please confirm the reason behind foreach loop giving error as "invalid token" and "splittedText" as does not exist in current context?

string[] splittedText = File.ReadAllLines(#"file.txt");//.Split(',');
foreach (string data in splittedText)
{
}
I want to read through a file in c# which returns array of string type. Then, I will be iterating over the array to fetch my desired data.
If you want to read a CSV file, you should use a CVS parser. Values in the CSV file are separated using command and in some cases, the value in the CSV file can also contain a comma. In that case, the column values are wrapped in double-quotes. And this solution will not handle that scenario.
var splittedText = File.ReadAllText("E:\\Test.txt").Split(',');
foreach (string data in splittedText)
{
Console.WriteLine(data.Trim());
}
Hint - Reading file line by line or Reading whole file content depends on your use case. May be below code snippet give some idea on how to split the content.
Please try.
var inputtext = File.ReadAllText(#"inpufile.txt");
inputtext.Replace("\n", "")
.Split(',',
StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.ToList().ForEach(t =>
{
System.Console.WriteLine(t);
//Other manupulations
});
if you want to split based on multiple characters , pass a character array to the split().
new char[] { ',', ':' };
Thank you.
You need change File.ReadAllLines to File.ReadAllText(path) then you can split method.

Trying to search for specific value within text file

I'm trying to search for a specific value within an array of files. I'm not sure what I'm missing here, but some insight would be great.
I've tried containing all lines from each file into an array that can be read from within an if statement.
void getAssetTag()
{
string path = #"\\SERVER\SHARE\FOLDER";
DirectoryInfo d = new DirectoryInfo(path);//Grabbing Directory
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
foreach (FileInfo file in Files)
{
string[] asset = File.ReadAllLines(file.FullName);
if (asset.Contains(AssetT.Text) == true) {
string allinfo = File.ReadAllText(file.FullName);
Results.Text = allinfo;
}
}
}
The results should output the entire data from the text file contained within AssetT.Textinto Results.Text.
asset is a string[], where each string is a line of text. When you do if (asset.Contains(AssetT.Text)), you're comparing an entire line to AssetT.Text.
If you want to find out if any single line contains AssetT.Text, then we need to call Contains on the line, not the array:
if (asset.Any(line => line.Contains(AssetT.Text))
Also, you're ending up reading the file twice here, once when you do ReadAllLines, and again when you do ReadAllText. Since it seems you will always read the whole file (either to determine that the file doesn't contain the text, or to get all the contents because it does contain the text), you should just do it once.
If you use File.ReadAllText in the beginning, now we have a string representation of the entire file which we can call .Contains on:
foreach (FileInfo file in new DirectoryInfo(path).GetFiles("*.txt"))
{
string asset = File.ReadAllText(file.FullName);
if (asset.Contains(AssetT.Text))
{
Results.Text = asset;
// No use reading more files unless we're going
// to save the contents to another variable
break;
}
}
Note that we break out of the loop since it appears you're setting the contents of the file to a single field of some class, so searching for more files will just overwrite any previous results found.
This can be simplified further using System.Linq extension methods and method chaining. We can also use Directory.GetFiles (which returns a list of file paths) instead, since we don't need a full-blown FileInfo object:
Results.Text = Directory
.GetFiles(path, "*.txt")
.Select(File.ReadAllText)
.FirstOrDefault(fileText => fileText.Contains(AssetT.Text)) ?? Results.Text;

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.

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

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.

How do I retrieve the value of a string from a list of .cs files?

I have a list of .cs files, each of which contain a string commandID. I need to retrieve the value of this string.
How do I implement this search and retrieve value mechanism in C#?
//Sample code to list all .cs files within a directory
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.cs");
// Sample code to read 1 file.
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\Public\TestFolder\file1.cs");
// Display the file contents by using a foreach loop.
foreach (string line in lines)
{
// INSERT YOUR SEARCH LOGIC HERE
}
I am assuming that, there is some string named CommandId in your .Cs files in your project and you are trying to get the value of it because you donot want to manually go to each file and get its value.
Follow the following
1- Paste all the .CS files in a separate folder.
2- Use FileSytem to get all the files in that folder
3- Use stream reader to get the text in the .cs files
4- compare each line in the file with the text you want to find.
5- If the string matches, the save it somewhere like XML or another text file.
6- Read the next file and Go back to step 3.
Finally got the ID out of it :)
let's say you have found the line you want, so I get the ID out of the line like :
string line = "while(i<10){CommandID = 15852; i+=1;}";
//I've put a complicated code in the string to make you sure
var rightSideOfAssignment = line.Split(new string[] {"CommandID"}, StringSplitOptions.RemoveEmptyEntries)[1];
int val = 0,temp;
bool hasAlreadyStartedFetchingNumbers= false;
foreach (char ch in rightSideOfAssignment) //iterate each charachter
{
if (int.TryParse(ch.ToString(), out temp)) //if ch is a number
{
foundFirstInteger = true;
val *= 10;
val += temp;
}
else
{
if (hasAlreadyStartedFetchingNumbers)
break;
//If you don't check this condition, it'll result to 158521
//because after hitting `;` it won't stop searching
}
}
MessageBox.Show(val.ToString()); //shows 15852

Categories

Resources