How to read serial number from text file - c#

I have a text file which contain of lots of information, but i only want to show the serial number of the text file. I am able to read and show the whole line of the serial number in label, but i only required the serial number in the format of ["BcXXXXX"]. Anyone would able to guide through?
string path = #"D:\Sample.txt";
StringBuilder buffer = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
String str = sr.ReadLine();
if (Regex.IsMatch(str, "Bc"))
buffer.Append(str);
string s = buffer.Append(str);
int start = s.IndexOf("["Bc") + 1;
int end = s.IndexOf(""]" , start);
string result = s.Substring(start, end - start);
label2.Text = result.ToString();
}

string serialNumber = System.IO.File.ReadLines(#"D:\Sample.txt")
.Select(line =>
{
var match = System.Text.RegularExpressions.Regex.Match(line, #"^\[""(.*)""\]$");
return match.Success ? match.Groups[1].Value : null;
}).FirstOrDefault(sn => sn != null);

Related

How to loop through the whole text file?

i need your help!, i am working on a script that, takes the string from a text file that grabs a value from the text file 20 characters.
Now i want to add spaces in front of character that was grabbed from the text file. However, i want to apply it to the whole text file.
For example:
Text 1 A (input):
01253654758965475896N12345
012536547589654758960011223325
(output):
(added 10 spaces in front)01253654758965475896 N12345
(added 10 spaces in front)01253654758965475896 0011223325
The idea is to loop through them, i added 10x spaces in front of and then also added spaces after 01253654758965475896.
Here is my code:
class Program
{
[STAThread]
static void Main(string[] args)
{
int acc = 1;
string calcted = (acc++).ToString().PadLeft(20, '0');
string ft_space = new string(' ', 12);
string path = Console.ReadLine();
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadToEnd()) != null)
{
string px = s;
string cnd = s.Substring(0, 16);
string cdr = cnd;
px = ft_space + cdr;
Console.Write("Enter Location:");
string pt1 = Console.ReadLine();
if (!File.Exists(pt1))
{
using (TextWriter sw = File.CreateText(pt1))
{
sw.Write(px);
}
}
} Console.ReadKey();
}
}
}
}
As noted in the comments, first change ReadToEnd to ReadLine.
ReadToEnd will read all the file, ReadLine will read one line every loop iteration.
Then, since you want 20 characters and not 16, you need to change s.Substring(0, 16) to s.Substring(0, 20).
After that you need to obtain the rest of the line, so that will be s.Substring(20).
You then need to concatenate all the parts together like this:
string result = spaces10 + first_part + spaces3 + second_part;
Another problem is that you just write the first line since you check if the file exists every time on the loop and you don't write the line if the file exists.
Here is how your code will look after such changes (and others):
string spaces10 = new string(' ', 10);
string spaces3 = new string(' ', 3);
string input_file = Console.ReadLine();
Console.Write("Enter Location:");
string output_file = Console.ReadLine();
using (StreamReader sr = File.OpenText(input_file))
{
using (TextWriter sw = File.CreateText(output_file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string first_part = line.Substring(0, 20);
string second_part = line.Substring(20);
string result = spaces10 + first_part + spaces3 + second_part;
sw.WriteLine(result);
}
}
}
Console.ReadKey();

Union of million line urls in 2 files

File A B contains million urls.
1, go through the url in file A one by one.
2, extract subdomain.com (http://subdomain.com/path/file)
3, if subdomain.com exist file B, save it to file C.
Any quickest way to get file C with c#?
Thanks.
when i use readline, it have no much different.
// stat
DateTime start = DateTime.Now;
int totalcount = 0;
int n1;
if (!int.TryParse(num1.Text, out n1))
n1 = 0;
// memory
dZLinklist = new Dictionary<string, string>();
// read file
string fileName = openFileDialog1.FileName; // get file name
textBox1.Text = fileName;
StreamReader sr = new StreamReader(textBox1.Text);
string fullfile = File.ReadAllText(#textBox1.Text);
string[] sArray = fullfile.Split( '\n');
//IEnumerable<string> sArray = tool.GetSplit(fullfile, '\n');
//string sLine = "";
//while (sLine != null)
foreach ( string sLine in sArray)
{
totalcount++;
//sLine = sr.ReadLine();
if (sLine != null)
{
//string reg = "http[s]*://.*?/";
//Regex R = new Regex(reg, RegexOptions.Compiled);
//Match m = R.Match(sLine);
//if(m.Success)
int length = sLine.IndexOf(' ', n1); // default http://
if(length > 0)
{
//string urls = sLine.Substring(0, length);
dZLinklist[sLine.Substring(0,length)] = sLine;
}
}
}
TimeSpan time = DateTime.Now - start;
int count = dZLinklist.Count;
double sec = Math.Round(time.TotalSeconds,2);
label1.Text = "(" + totalcount + ")" + count.ToString() + " / " + sec + " = " + (Math.Round(count / sec,2)).ToString();
sr.Close();
I would go for using Microsoft LogParser for processing big files: MS LogParser. Are you limited to implement it in described way only?

Extract data from text file

I need to extract some data from a text file and insert to columns in excel sheet. I know how to do this if the rows and the length of the string is known.
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader("test.txt")
{
string line;
while ((line = sr.ReadLine()) != null)
{
listSNR.Items.Add(line.Substring (78,4));
}
}
}
But the particular text file is complex and the starting index or the length cannot be provided. But the starting word (PCPU01) of the row is known.
Eg: PCPU01,T2716,0.00,0.01,0.00,0.00
output:
T2716 0 0.01 0 0
In that case can somebody please let me know how to extract the texts?
using(System.IO.StreamReader sr = new System.IO.StreamReader("test.txt"))
{
string line;
while((line = sr.ReadLine()) != null)
{
string[] split = line.Split(',');
//...
}
}
split[0] will return "PCPU01", split[1] "T2716" and so on.
You can split one string into an array of strings, separated by a given character. This way, you could split the source string by a comma and use the resulting strings to build your output. Example:
string source = "PCPU01,T2716,0.00,0.01,0.00,0.00";
string[] parts = source.Split(',');
StringBuilder result = new StringBuilder();
result.Append(parts[1]); // The second element in the array, i.e. T2716
result.Append(" ");
result.Append(parts[2]); // 0.00
... // And so on...
return result.ToString() // return a string, not a StringBuilder
I hope this helps a little bit. You might have to tweak it to your needs. But this is a higher level code that gives you general idea of extracting data off a notepad.
DialogResult result = openFileDialog.ShowDialog();
Collection<Info> _infoCollection = new Collection<Info>();
Collection<string> listOfSubDomains = new Collection<string>();
string[] row;
string line;
// READ THE FILE AND STORE IT IN INFO OBJECT AND STORE TAHT INFO OBJECT IN COLLECTION
try
{
using (StreamReader reader = new StreamReader(openFileDialog.FileName))
{
while((line = reader.ReadLine()) != null)
{
Info _info = new Info();
row = line.Split(' ');
_info.FirstName = row[0];
_info.LastName = row[1];
_info.Email = row[2];
_info.Id = Convert.ToInt32(row[3]);
_infoCollection.Add(_info);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
thanks for the answers. What i wanted is to identify the particular line in the text file and split the line into columns. So i was able to do this by calling a GetLine method:
string line15=GetLine(#"test.txt",15);
public string GetLine(string fileName, int line)
{
using (System.IO.StreamReader ssr = new System.IO.StreamReader("test.txt"))
//using (var ssr = new StreamReader("test.txt"))
{
for (int i = 1; i < line; i++)
ssr.ReadLine();
return ssr.ReadLine();
}
}
Then i splitted this line by using the delimiter (,)
This was my approach in C#. It takes a string input (which you can get out of a text file) and an int with which line you want to get. It then separates the string at a given seperator char to a list which in turn is then read out. If the given line number is lower than the count of the created list, the entry is given back.
public string GetLine(string multiline,int line)
{
List<string> lines = new List<string>();
lines = multiline.Split('\n').ToList<string>();
return lines.Count >= line ? lines[line] : "";
}

Reading a null-terminated string

I am reading strings from a binary file. Each string is null-terminated. Encoding is UTF-8. In python I simply read a byte, check if it's 0, append it to a byte array, and continue reading bytes until I see a 0. Then I convert byte array into a string and move on. All of the strings were read correctly.
How can I read this in C#? I don't think I have the luxury of simply appending bytes to an array since the arrays are fixed size.
Following should get you what you are looking for. All of text should be inside myText list.
var data = File.ReadAllBytes("myfile.bin");
List<string> myText = new List<string>();
int lastOffset = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] == 0)
{
myText.Add(System.Text.Encoding.UTF8.GetString(data, lastOffset, i - lastOffset));
lastOffset = i + 1;
}
}
I assume you're using a StreamReader instance:
StringBuilder sb = new StringBuilder();
using(StreamReader rdr = OpenReader(...)) {
Int32 nc;
while((nc = rdr.Read()) != -1) {
Char c = (Char)nc;
if( c != '\0' ) sb.Append( c );
}
}
You can either use a List<byte>:
List<byte> list = new List<byte>();
while(reading){ //or whatever your condition is
list.add(readByte);
}
string output = Encoding.UTF8.GetString(list.ToArray());
Or you could use a StringBuilder :
StringBuilder builder = new StringBuilder();
while(reading){
builder.Append(readByte);
}
string output = builder.ToString();
If your "binary file" only contains null terminated UTF8 strings, then for .NET it isn't a "binary file" but just a text file because null characters are characters too. So you could just use a StreamReader to read the text and split it on the null characters.
(Six years later "you" would presumably be some new reader and not the OP.)
A one line (ish) solution would be:
using (var rdr = new StreamReader(path))
return rdr.ReadToEnd().split(new char[] { '\0' });
But that will give you a trailing empty string if the last string in the file was "properly" terminated.
A more verbose solution that might perform differently for very large files, expressed as an extension method on StreamReader, would be:
List<string> ReadAllNullTerminated(this System.IO.StreamReader rdr)
{
var stringsRead = new System.Collections.Generic.List<string>();
var bldr = new System.Text.StringBuilder();
int nc;
while ((nc = rdr.Read()) != -1)
{
Char c = (Char)nc;
if (c == '\0')
{
stringsRead.Add(bldr.ToString());
bldr.Length = 0;
}
else
bldr.Append(c);
}
// Optionally return any trailing unterminated string
if (bldr.Length != 0)
stringsRead.Add(bldr.ToString());
return stringsRead;
}
Or for reading just one at a time (like ReadLine)
string ReadNullTerminated(this System.IO.StreamReader rdr)
{
var bldr = new System.Text.StringBuilder();
int nc;
while ((nc = rdr.Read()) > 0)
bldr.Append((char)nc);
return bldr.ToString();
}

Read until condition is met and read next line storing it as an array

I currently have a conf file which exists out of the following format:
[client]
person1,person2,person3,person4
[employee]
emp1,emp2,emp3,mp4
And so on. Now I need to read the file to store the data that comes after the line [employee] into and array.
As a quick draft, try something like this:
string[] readAllLines = File.ReadAllLines("path/to/file");
for (int i = 0; i < readAllLines.Length-1; i++)
{
if (readAllLines[i].StartsWith("[employee]"))
{
string[] employees = readAllLines[i + 1].Split(',');
// Do something
}
}
Untested Code:
static class SubstringExtensions
{
/// <summary>
/// Get string value after [last] a.
/// </summary>
public static string After(this string value, string a)
{
int posA = value.LastIndexOf(a);
if (posA == -1)
{
return "";
}
int adjustedPosA = posA + a.Length;
if (adjustedPosA >= value.Length)
{
return "";
}
return value.Substring(adjustedPosA);
}
}
Read the File:
System.IO.StreamReader myFile = new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
string[] split = myString.After("[employee]").Split(',');
Not the most cool or elegant way, but the way you described it would work like this.
StreamReader reader = new StreamReader("path to your config file");
string text = reader.ReadToEnd();
text = text.Substring(text.IndexOf("[employee]"), 25);
text = text.Replace("[employee]\r\n", "");
string[] array = text.Split(',');

Categories

Resources