I have a text file which when opened in Editpad Lite show the number of lines as 2754813 and when it is opened in Windows Notepad showing the number of lines as 2713520. When I read it with a C# programme, it shows the number of lines contained in the text file as 2713520 i.e. the same as in notepad. Wordwrap is turned off in both cases This prevents me from matching the lines with Editpad text file. Would anyone please offer their valuable comment.
int b = 0;
using (StreamWriter Writer = new StreamWriter(path_to_textfile.txt"))
{
using (StreamReader Reader = new StreamReader(lisfile))
{
while ((line = Reader.ReadLine()) != null)
{
Match match = Regex.Match(line, #"");//line break symbol between quotes.
if (match.Success)
{
b++;
if (b == 100000) //I got the count of lines correctly.
{
Writer.WriteLine(line);
}
}
else
{
//Writer.WriteLine(line);
}
}
}
}
Related
I'm a blind person and I'm trying to create a win form app that aims to help people with visual impairments to learn better the keyboard. There are different levels in this program. such as: match characters, match words and match sentences. Almost I finished everything, but I miss the technique of storing txt files in the source code in order to be invisible to the user in the program files.
Any suggestion?
You can use the StreamWriter method.
https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter?view=net-7.0
A complete example:
internal class Program
{
static void Main(string[] args)
{
// Get the directories currently on the C drive.
DirectoryInfo[] cDirs = new DirectoryInfo(#"c:\").GetDirectories();
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("Demo.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader("Demo.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
I have .text File (with 400K rows). I need to read that file and If i find (AB,CB,DE,FG) in certain position (35, 2) in each row, I need to replace that with new value which I already have in dictionary object.
this is my dictionary with list of policy number and respective group:
ListofPolicy[10001,MM]
ListofPolicy[10005,KK]
ListofPolicy[10011,NN]
ListofPolicy[10018,YY]
ListofPolicy[10020,GG]
etc...
This is my sample .txt file: I need to read the line.Substring(35, 2) will tell us which group it is.
P00002398911100010131220111061553XXAB549099QSTJDK6016
HUI001004117577408867289000000007209171
P00002398918100058882220111061459YYLT518435BIVQZC1855
P00002398916726561656220111103331XXKY518435BIVQZC1855
PPP001CSTON
P00002398911001136778220111103329XXCB511100QSBUPO1128
HUI001004117577408867289000000007209171
P00002398911001888877220111103323XXKI518435BIVQZC1855
PMT001CSTON
P00002398911002066656220111103320YYFG511100QSBUPO1128
HUI001004117183000000007209169
P00002398917409185763220111103316XXDF511100QSBUPO1128
How do I approach this ?
If I understand you correctly, you need something like that:
string content = "";
using (StreamReader sr = new StreamReader("path\\to\\your\\file.txt"))
{
content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("path\\to\\your\\file.txt"))
{
foreach (string line in content.Split('\n'))
{
if (yourDictionary.Keys.Contains(line.Substring(35, 2)))
{
sw.WriteLine($"{line.Substring(0, 35)}{yourDictionary[line.Substring(35, 2)]}{line.Substring(37, line.Length - 37)}");
}
else
{
sw.WriteLine(line);
}
}
}
I use the below method to remove all blank lines from a file but it is for some reason adding an extra line at the end of the document?
var tempFileName = Path.GetTempFileName();
try
{
using (var streamReader = new StreamReader(file))
using (var streamWriter = new StreamWriter(tempFileName))
{
string line;
while ((line = streamReader.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
streamWriter.WriteLine(line);
}
}
File.Copy(tempFileName, file, true);
}
finally
{
File.Delete(tempFileName);
}
How do I fix this?
Also can the code be made shorter?
Also can the code be made shorter?
A more efficient solution to the other answer:
File.WriteAllLines(file, File.ReadLines("some/path").Where(l => !string.IsNullOrWhiteSpace(l)));
File.ReadLines() is more efficient than File.ReadAllLines() because it allows you to query the IEnumerable<string> without reading it all into memory first.
We then take the resulting IEnumerable<string> from our Where() method and pass it to an overload of File.WriteAllLines() which takes an IEnumerable<string> as its second parameter.
StreamWriter.WriteLine() will always append a new line (a carriage return, line feed pair) after the string, so I assume that's what you're referring to. To me, it's normal and best to have the last line followed by a new line. But if you don't want it, don't write one.
As far as the length of your code, it looks about right to me. If it seems to detract from your program logic, just move it into its own method.
For efficiency, you might try deleting the original file and then renaming the temporary file. That would be more efficient than copying the entire file.
var tempFileName = Path.GetTempFileName();
try
{
using (var streamReader = new StreamReader(file))
using (var streamWriter = new StreamWriter(tempFileName))
{
string line;
bool isFirstLine = true;
while ((line = streamReader.ReadLine()) != null)
{
if (!string.IsNullOrWhiteSpace(line))
{
if (!isFirstLine)
streamWrite.WriteLine();
streamWriter.Write(line);
isFirstLine = false;
}
}
}
File.Delete(file);
File.Move(tempFileName, file);
}
finally
{
File.Delete(tempFileName);
}
The problem is that StreamReader.ReadLine does not return the line breaks themselves, thus destroying line break information. In other words, those two input files:
File 1: A\r\nB\r\n
File 2: A\r\nB
Will yield the same input to your method. You can't determine that way whether there was a final line break or not.
If you never want a final line break, use Write instead of WriteLine and manually add a line break at the beginning of your loop in every iteration except for the first one:
...
string line;
bool first = true;
while ((line = streamReader.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line))
continue;
if (!first)
streamWriter.WriteLine();
streamWriter.Write(line);
first = false;
}
...
I have the following code in C# that writes an array of lines to a file. The difference between this and File.WriteAllLines(string, string[]); is that mine does not leave an extra newline at the end.
public static void WriteAllLinesCompact(string path, IEnumerable<string> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
bool isFirst = true;
using (FileStream stream = File.OpenWrite(path))
using (StreamWriter writer = new StreamWriter(stream))
{
foreach (string line in contents)
{
if (isFirst)
{
writer.Write(line);
isFirst = false;
continue;
}
writer.Write("\r\n" + line);
}
}
}
The problem is that it does not terminate the file after the last line. For example, if the last line was "text = absolute", after replacing the last line with "tempor" and saving using the above method, the file's last line would be "tempor absolute" instead of just "tempor".
Please let me know if you need more information.
EDIT : I will try to explain more clearly what happens in the replace process.
Step 1 : Load any .txt file with File.ReadAllLines(string);
Step 2 : Replace the last line with one that's shorter than the previous one. For example, if the length of the last value was 10 chars, the new one should perhaps be 7 chars.
Step 3 : Save using the given method to the same file as before.
As suggested via comments, the best solution in this kind of situations is keeping it simple and relying on a for-sure-working solution. For example:
bool isFirst = true;
using (StreamWriter writer = new StreamWriter(path))
{
foreach (string line in contents)
{
if (isFirst)
{
writer.Write(line);
isFirst = false;
continue;
}
writer.Write(Environment.NewLine + line);
}
}
Personally, I would prefer to use writer.WriteLine, but it would go against the OP's requirement of not including a final new line.
I am reading a huge file (hundreds of MB) and displaying it to a richtext box. my program would freeze when I run it. can anybody give me advice? is is because the way I read the file? or is it because there is somekind of limit on richtextbox ? I tried to increase the maxLength properties 2147483647, but it says "property value is not valid is not a valid value for INt32" . My application is 64 bit so why this happens? and how do I make the int32 to be 64 ?
StreamReader sr = new StreamReader(file_name1);
string myLine;
while ((myLine = sr.ReadLine()) != null)
{
richTextBox1.AppendText(myLine+"\n");
count_lines++;
}
sr.Close();
textBox2.Text = count_lines.ToString(); ;
(I'll respond to your comment as an answer, to enhance the readability)
Q: (by John Ryann )
would it be possible to apply pattern for either richTextBox.LoadFile
or File.ReadAllText()? meaning would it be possible to only get lines
which has/which contains a certain string?
A:
StreamReader sr = new StreamReader("#c:\MyBigFile.log");
string line = sr.ReadLine();
while (line != null)
{
if(line.Contains("Error"))
{
richTextBox.Text += line + Environment.NewLine;
}
line = sr.ReadLine();
}
sr.Close();