I am coding a program, and i use stream writer, to write text to some files. The problem is, that when it writes to the text file, it leaves an unwanted extra line to the file, which confuses my program, when try to read it later. An example of the stream writer that i use is this:
string enbl = "Enabled = false;";
string path = Directory.GetCurrentDirectory();
System.IO.StreamWriter file = new System.IO.StreamWriter("path");
file.WriteLine(enbl);
file.Close();
Is it possible ti fix that ?
When you dont want that the output get an implicit CR+LF (0x0D + 0x0A) at the end you have to you use file.Write(enbl); instead of file.WriteLine(enbl);
Just use Write instead of WriteLine method.
Related
I have a strange problem with StreamReader. My program is a console program and it should loop through a directory structure for all *.cs file. Then check if a specific word is in the file and write the file path to output.
using (StringReader sr = new StringReader(fPath))
{
string content = sr.ReadLine(); // sr.ReadToEnd();
Debug.WriteLine(content);
int found = content.IndexOf(p);
if (found != -1)
{
result = true;
}
}
This is the code that I use to find the work in a specific file.
The problem is that sr.ReadToEnd (but also ReadLine) returns the value of fPath not the content of the file!
The file exists and is not locked.
If fPath is:
"C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
content will be:
"C:\TEMP\DC_LV1_LaMine_Mk2Plus_134_ix220_20160404\Alarm.Script.cs"
Can anyone see what I have done wrong?
You are using StringReader instead of StreamReader
StringReader implements a TextReader that reads from a string
StramReader implements a TextReader that reads characters from a byte stream in a particular encoding
If you want to read from a file use this constructor for StreamReader
You could also use File.ReadAllText if the file is small and you have enough resources to read it all at once
For a more comprehensive overview, see this article
I have a small HttpWebRequest that grabs some text from a online .txt file
After it gets it i want to save it to a .txt file on the computer.
Content of the text is formatet like this:
Line one
Line two
Line four
Line Five
Line ten etc.
But when it saves it ends up like this:
Line oneLine twoLine fourLine FiveLine ten etc.
How may I fix this?
Code is as follows:
HttpWebRequest WebReq3 = (HttpWebRequest)WebRequest.Create("http://test.net/test.txt");
HttpWebResponse WebResp3 = (HttpWebResponse)WebReq3.GetResponse();
System.IO.StreamReader sr3 = new System.IO.StreamReader(WebResp3.GetResponseStream());
System.IO.StreamWriter _WriteResult = new StreamWriter(Application.StartupPath + "\Test.txt");
_WriteResult.Write(sr3.ReadToEnd());
_WriteResult.Close();
sr3.Close();
Read data using ReadLine() and write using WriteLine() instead of ReadToEnd() and WriteToEnd().
Remove this line:
_WriteResult.Write(sr3.ReadToEnd());
And modify your code with this:
string readval = sr3.ReadLine();
while(readval != null)
{
_WriteResult.WriteLine(readval);
readval = sr3.ReadLine();
}
For more details, see the documentation.
I have a large text file with a lot of \n that I need to replace with \r\n. With small text files, I was using the ReadToEnd method to get the file as a string and then use the Replace method and then write the string to a file. With a big file, however, I get an OutOfMemory exception because the string is too big. Any help would be greatly appreciated. Thanks.
private void foo() {
StreamReader reader = new StreamReader(#"D:\InputFile.txt");
StreamWriter writer = new StreamWriter(#"D:\OutputFile.txt");
string currentLine;
while (!reader.EndOfStream) {
currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
reader.Close();
writer.Close();
}
This should resolve your problem. Please note, that reader.ReadLine() cuts of the trailing "\n".
DiableNoir's solution is the right idea, but the implementation is buggy and it needs some explanation. Here's an improved one:
using (var reader = new StreamReader(#"D:\InputFile.txt"))
using (var writer = new StreamWriter(#"D:\OutputFile.txt")) // or any other TextWriter
{
while (!reader.EndOfStream) {
var currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
}
You use a TextReader for input and a TextWriter for output (this one might direct to a file or to an in-memory string). reader.ReadLine will not return the line ending as part of the line, so you need to write it explicitly (instead of using string.Replace, which will not accomplish anything at all).
Also, exactly because you will never see \n or \r as part of currentLine, this program is safe to run again on the output it has produced (in this case its output will be exactly identical to its input). This would not be the case if currentLine included the line ending, because it would change \n to \r\n the first time, and then make it \r\r\n the second time, etc.
You could use Read and specify how many bytes to read each time. Such as read the file in 10 MB chunks.
Or if you need like a larger buffer you can use StreamReader.ReadBlock();
If certain conditions are met, I want to copy a file from one directory to another WITHOUT deleting the original file. I also want to set the name of the new file to a particular value.
I am using C# and was using FileInfo class. While it does have CopyTo method. It does not give me the option to set the file name. And the MoveTo method while allowing me to rename the file, deletes the file in the original location.
What is the best way to go about this?
System.IO.File.Copy(oldPathAndName, newPathAndName);
You may also try the Copy method:
File.Copy(#"c:\work\foo.txt", #"c:\data\bar.txt")
Use the File.Copy method instead
eg.
File.Copy(#"C:\oldFile.txt", #"C:\newFile.txt");
You can call it whatever you want in the newFile, and it will rename it accordingly.
If you want to use only FileInfo class
try this
string oldPath = #"C:\MyFolder\Myfile.xyz";
string newpath = #"C:\NewFolder\";
string newFileName = "new file name";
FileInfo f1 = new FileInfo(oldPath);
if(f1.Exists)
{
if(!Directory.Exists(newpath))
{
Directory.CreateDirectory(newpath);
}
f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
}
One method is:
File.Copy(oldFilePathWithFileName, newFilePathWithFileName);
Or you can use the FileInfo.CopyTo() method too something like this:
FileInfo file = new FileInfo(oldFilePathWithFileName);
file.CopyTo(newFilePathWithFileName);
Example:
File.Copy(#"c:\a.txt", #"c:\b.txt");
or
FileInfo file = new FileInfo(#"c:\a.txt");
file.CopyTo(#"c:\b.txt");
StreamReader reader = new StreamReader(Oldfilepath);
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter(NewFilePath);
writer.Write(fileContent);
File.Copy(#"C:\oldFile.txt", #"C:\newFile.txt", true);
Please do not forget to overwrite the previous file! Make sure you add the third param., by adding the third param, you allow the file to be overwritten. Else you could use a try catch for the exception.
Regards,
G
You can use the Copy method in the System.IO.File class.
The easiest method you can use is this:
System.IO.File.Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName);
This will take care of everything you requested.
You can use either File.Copy(oldFilePath, newFilePath) method or other way is, read file using StreamReader into an string and then use StreamWriter to write the file to destination location.
Your code might look like this :
StreamReader reader = new StreamReader("C:\foo.txt");
string fileContent = reader.ReadToEnd();
StreamWriter writer = new StreamWriter("D:\bar.txt");
writer.Write(fileContent);
You can add exception handling code...
I have a few multimillion lined text files located in a directory, I want to read line by line and replace “|” with “\” and then write out the line to a new file. This code might work just fine but I’m not seeing any resulting text file, or it might be I’m just be impatient.
{
string startingdir = #"K:\qload";
string dest = #"K:\D\ho\jlg\load\dest";
string[] files = Directory.GetFiles(startingdir, "*.txt");
foreach (string file in files)
{
StringBuilder sb = new StringBuilder();
using (FileStream fs = new FileStream(file, FileMode.Open))
using (StreamReader rdr = new StreamReader(fs))
{
while (!rdr.EndOfStream)
{
string begdocfile = rdr.ReadLine();
string replacementwork = docfile.Replace("|", "\\");
sb.AppendLine(replacementwork);
FileInfo file_info = new FileInfo(file);
string outputfilename = file_info.Name;
using (FileStream fs2 = new FileStream(dest + outputfilename, FileMode.Append))
using (StreamWriter writer = new StreamWriter(fs2))
{
writer.WriteLine(replacementwork);
}
}
}
}
}
DUHHHHH Thanks to everyone.
Id10t error.
Get rid of the StringBuilder, and do not reopen the output file for each line:
string startingdir = #"K:\qload";
string dest = #"K:\D\ho\jlg\load\dest";
string[] files = Directory.GetFiles(startingdir, "*.txt");
foreach (string file in files)
{
var outfile = Path.Combine(dest, Path.GetFileName(file));
using (StreamReader reader = new StreamReader(file))
using (StreamWriter writer = new StreamWriter(outfile))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine(line.Replace("|", "\\"));
line = reader.ReadLine();
}
}
}
Why are you using a StringBuilder - you are just filling up your memory without doing anything with it.
You should also move the FileStream and StreamWriter using statements to outside of your loop - you are re-creating your output streams for every line, causing unneeded IO in the form of opening and closing the file.
Use Path.Combine(dest, outputfilename), from your code it looks like you're writing to the file K:\D\ho\jlg\load\destouputfilename.txt
This code might work just fine but I’m not seeing any resulting text file, or it might be I’m just be impatient.
Have you considered having a Console.WriteLine in there to check the progress. Sure, it's going to slow down performance a tiny tiny bit - but you'll know what's going on.
It looks like you might want to do a Path.Combine, so that instead of new FileStream(dest + outputfilename), you have new FileStream(Path.Combine(dest + outputfilename)), which will create the files in the directory that you expect, rather than creating them in K:\D\ho\jlg\load.
However, I'm not sure why you're writing to a StringBuilder that you're not using, or why you're opening and closing the file stream and stream writer on each line that you're writing, is that to force the writer to flush it's output? If so, it might be easier to just flush the writer/stream on each write.
you're opening and closing the output strean for each line in the output, you'll have to be very patient!
open it once outside the loop.
I guess the problem is here:
string begdocfile = rdr.ReadLine();
string replacementwork = docfile.Replace("|", "\\");
you're reading into begdocfile variable but replacing chars in docfile which I guess is empty
string replacementwork = docfile.Replace("|", "\\");
I believe the above line in your code is incorrect : it should be "begdocfile.Replace ..." ?
I suggest you focus on getting as much of the declaration and "name manufacture" out of the inner loop as possible : right now you are creating new FileInfo objects, and path names for every single line you read in every file : that's got to be hugely expensive.
make a single pass over the list of target files first, and create, at one time, the destination files, perhaps store them in a List for easy access, later. Or a Dictionary where "string" will be the new file path associated with that FileInfo ? Another strategy : just copy the whole directory once, and then operate to directly change the copied files : then rename them, rename the directory, whatever.
move every variable declaration out of that inner loop, and within the using code blocks you can.
I suspect you are going to hear from someone here at more of a "guru level" shortly who might suggest a different strategy based on a more profound knowledge of streams than I have, but that's a guess.
Good luck !