I am trying to read a file I create that contains all the logs lines throughout my program. I have the following cod:
private string ReadEmailLog(string EmailLog)
{
TextReader tr = new StreamReader(EmailLog);
tr.ReadLine();
tr.Close();
}
I need to read the EmailLog file, every line of it, and then put return it into a string called message. How would I get this method to return the whole log file, every line?
You can use File.ReadAllText or File.ReadAllLines.
If you're using .NET 4.0, you can also use File.ReadLines:
var files = from file in Directory.EnumerateFiles(#"c:\",
"*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("Microsoft")
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
}
This allows you to make file I/O part of a LINQ operation.
Try
tr.ReadToEnd();
which will return a string that contains all the content of your file.
TextReader.ReadToEnd Method
If you want to get the lines in a string[], then
tr.ReadToEnd().Split("\n");
should do it, while it will separate the lines to the "\n" character, which represents a carriage return and line feed combined characters (new line character).
simply use:
String text = tr.ReadToEnd();
You can read all the contents or the log and return it. For example:
private string void ReadEmailLog(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
return logreader.ReadToEnd();
}
}
Or if you want each line one at a time:
private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
string line = logreader.ReadLine();
while(line != null)
{
yield return line;
}
}
}
tr.ReadToEnd(); //read whole file at once
// or line by line
While ( ! tr.EOF)
tr.ReadLine()//
Related
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);
}
}
}
Been looking through other people's answers and nothing seems to work.
Here is my code:
public void TaskOnClick() //getting multi-values
{
foreach (string inputJson in File.ReadLines("Assets/Text/multi-import.txt"))
{
string temperature = GetTemperatureByRegex(inputJson);
Debug.Log(temperature);
string filename = "Assets/Text/TEMP/multi-export.txt";
{
using (StreamWriter writeFile = new StreamWriter(filename, false))
{
writeFile.AutoFlush = true;
Console.SetOut(writeFile);
writeFile.WriteLineAsync(temperature.ToString());
}
}
}
}
The idea is that my parsing script gets my data and then streamwriter writes the data to a txt file. Problem is that streamwriter keeps appending the txt file instead of overwriting the file.
Whenever I try to use filestream it overwrites the file, yes, but only the first line of the data gets written, no matter what I tried.
My username speaks for itself...
What you do wrong is creating StreamWriter inside a loop. If you provide an overwrite settings it will only write 1 line.
public void TaskOnClick() //getting multi-values
{
string filename = "Assets/Text/TEMP/multi-export.txt";
using (StreamWriter writeFile = new StreamWriter(filename, false))
{
foreach (string inputJson in File.ReadLines("Assets/Text/multi-import.txt"))
{
string temperature = GetTemperatureByRegex(inputJson);
Debug.Log(temperature);
writeFile.AutoFlush = true;
Console.SetOut(writeFile);
writeFile.WriteLine(temperature.ToString());
}
}
}
But there is a shorter way of doing this with the help of LINQ.
public void TaskOnClick() //getting multi-values
{
string filename = "Assets/Text/TEMP/multi-export.txt";
var tempratures = File.ReadAllLines("Assets/Text/multi-import.txt")
.Select(GetTemperatureByRegex).ToArray();
File.WriteAllLines(filename,tempratures); // it creates a new file or overwrites
}
I have to state that above method may be dangerous if input file is too large. Because it reads entire file into memory.
Why don’t you just delete the file before opening the stream writer?
if(File.Exists(filename)){
File.Delete(filename);
}
//here whatever you need to do next
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'm using the two functions to read and write huge files (write to multiple files). I want to keep the file operation in the functions because the lines may be read/write from other sources.
Update:
C# doesn't really have coroutine. Is it a good use case for Reactive extensions?
foreach (var line in ReadFrom("filename"))
{
try
{
.... // Some actions based on the line
var l = .....
WriteTo("generatedFile1", l);
}
catch (Exception e)
{
var l = ..... // get some data from line, e and other objects etc.
WriteTo("generatedFile2", l);
}
}
The following function open the file once until all the lines are read and then close and release the resource.
private static IEnumerable<string> ReadFrom(string file)
{
string line;
using (var reader = File.OpenText(file))
{
while ((line = reader.ReadLine()) != null)
yield return line;
}
}
However, the following function, which write the lines instead of read lines, open and close the file for each line it writes. Is it possible to implement it in a way so it only open the file once and continue to write to the file until EOF is sent?
private static void WriteTo(string file, string line)
{
if (!File.Exists(file)) // Remove and recreate the file if existing
using (var tw = File.CreateText(file))
{
tw.WriteLine(line);
}
else
using (var tw = new StreamWriter(file, true))
{
tw.WriteLine(line);
}
}
Just use File.WriteAllLines. It will write all of the lines in a sequence to a file, and it won't open/close the file for each line.
You can remove the entire second method, and replace the call with var writer = new StreamWriter(file, true), as that constructor creates the file if it does not exist.
You can then use writer.WriteLine() until you're done writing, and Dispose() it afterwards.
Lets say i have a text file with following content:
Hello!
How are you?
I want to call the file via a simple application that produces an output file with the following contents:
buildLetter.Append("Hello!").AppendLine();
buildLetter.Append("How are you?").AppendLine();
As you see, every line should be put between " ".
Any help will be appreciated.
void ConvertFile(string inPath, string outPath)
{
using (var reader = new StreamReader(inPath))
using (var writer = new StreamWriter (outPath))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());
line = reader.ReadLine ();
}
}
}
You should add some I/O exception handling on your own.
If you want to append "" to each line you could try combining the ReadAllLines and WriteAllLines methods:
File.WriteAllLines(
"output.txt",
File
.ReadAllLines("input.txt")
.Select(line => string.Format("\"{0}\"", line))
.ToArray()
);
Notice that this loads the whole file contents into memory so it wouldn't work well with very large files. In this case stream readers and writers are more adapted.
Use the StreamReader class from System.IO
Refer this link for sample code
All you probably need to do is change the line
Console.WriteLine(sr.ReadLine());
to
Console.WriteLine(""""" + sr.ReadLine() + """""); // handwritten code - not tested :-)
For a small text files this works for me.
private void EditFile(string path, string oldText, string newText)
{
string content = File.ReadAllText(path);
content = contenido.Replace(oldText, newText);
File.WriteAllText(path, content);
}