in a current development I'm stuck with a strang problem.
In a bunch of written files on my harddisk i want to read out their content and write it into a textbox. It seams very easy, but somehow i stuck in a catch:
The files are containing something like this: "<LogItem><Row Number="0"><Column Name="object_id"><Old Value="2317"/><New Value="2317"/>"
I read them with:
textBox1.Text = File.ReadAllText(filetoread);
The result of this "ReadAllTest" is only the first Char "<" everything else in not written into the textbox.
Manually I can read the file with the normal Editor and this shows the complete text.
Are there any traps or limitations a haven't seen?
Best regards
It could be a problem of encoding... Rare but not impossible... Try, one at a time:
textBox1.Text = File.ReadAllText(filetoread, Encoding.Unicode);
textBox1.Text = File.ReadAllText(filetoread, Encoding.BigEndianUnicode);
textBox1.Text = File.ReadAllText(filetoread, Encoding.UTF32);
textBox1.Text = File.ReadAllText(filetoread, Encoding.UTF8);
textBox1.Text = File.ReadAllText(filetoread, Encoding.Default);
If the answer by xanatos doesn't work, try this:
using (StreamReader read = new StreamReader(filetoread))
{
textBox1.Text = read.ReadToEnd();
}
It doesn't use File.ReadAllText() as you can see.
And, this will work.
Related
I'm trying to update an existing app.
I was asked previously to simply clean out an xml file for escape characters, which were coming to us, prior to them being pulled through to the company system. Doing this allowed us the option of avoiding writing inside an app written 7 years ago and working fine (but ZERO documentation)
It actually worked fine with
foreach (string d in Directory.GetFiles(test, "*.xml", SearchOption.AllDirectories))
{
String[] lines = File.ReadAllLines(d);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].Contains("&"))
{
i++;
}
//Replace incorrect characters
else if (lines[i].Contains("&"))
{
log.Info(saveName);
log.Error("Incorrect '&' Detected: Changing to '&'");
lines[i] = lines[i].Replace("&", "&");
log.Info(lines[i]);
}
}
System.IO.File.WriteAllLines(d, lines);
}
And maybe too easily as I have been asked to try to integrate this with the main app, to prevent the operators having to do the pre-clean.
I know (well I believe) that I am missing the corresponding System.IO.File.WriteAllLines(d, lines); in the following code but I can not get it or anything else to work.
The "replace" is working as the WriteLine is showing the corrected line(s) but I can not get the system to hold the changes.
MemoryStream ms = new MemoryStream();
ms.Position = 0;
List<string> rows = new List<string>();
using (var reader = new StreamReader(ms))
{
string line;
var sw = new StreamWriter(ms);
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("&"))
{
Console.WriteLine(line);
line = line.Replace("&", "&");
sw.Write(line);
Console.WriteLine(line);
}
}
Not sure how important for you is to write a log, but seems you can do the same using something like this:
string text = File.ReadAllText("test.xml");
text = Regex.Replace(text, "&(?!amp;)", "&");
File.WriteAllText("test.xml", text);
It should also cover the case when there are more then one & symbol in one string (the original code will not handle it - so if the sting is something like '&hello&', it will be processed as '&hello&').
Lesson is "when amending a large app, make sure to read it all".
For some reason the original developer decided to dip back in to the zip file (where these files were received) and extract the whole thing again for the Stream.
Changed that and it all works and is running much faster as a result.
Hi everyone beginner here looking for some advice with a program I'm writing in C#. I need to be able to open a text document, read the first line of text (that is not blank), save this line of text to another text document and finally overwrite the read line with an empty line.
This is what I have so far, everything works fine until the last part where I need to write a blank line to the original text document, I just get a full blank document. Like I mentioned above I'm new to C# so I'm sure there is an easy solution to this but I can't figure it out, any help appreciated:
try
{
StreamReader sr = new StreamReader(#"C:\Users\Stephen\Desktop\Sample.txt");
line = sr.ReadLine();
while (line == "")
{
line = sr.ReadLine();
}
sr.Close();
string path = (#"C:\Users\Stephen\Desktop\new.txt");
if (!File.Exists(path))
{
File.Create(path).Dispose();
TextWriter tw = new StreamWriter(path);
tw.WriteLine(line);
tw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine(line);
tw.Close();
}
StreamWriter sw = new StreamWriter(#"C:\Users\Stephen\Desktop\Sample.txt");
int cnt1 = 0;
while (cnt1 < 1)
{
sw.WriteLine("");
cnt1 = 1;
}
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
else
Console.WriteLine("Program Not Installed");
Console.ReadLine();
Unfortunately, you do have to go through the painstaking process of rewriting the file. In most cases, you could get away with loading it into memory and just doing something like:
string contents = File.ReadAllText(oldFile);
contents = contents.Replace("bad line!", "good line!");
File.WriteAllText(newFile, contents);
Remember that you'll have to deal with the idea of line breaks here, since string.Replace doesn't innately pay attention only to whole lines. But that's certainly doable. You could also use a regex with that approach. You can also use File.ReadAllLines(string) to read each line into an IEnumerable<string> and test each one while you write them back to the new file. It just depends on what exactly you want to do and how precise you want to be about it.
using (var writer = new StreamWriter(newFile))
{
foreach (var line in File.ReadAllLines(oldFile))
{
if (shouldInsert(line))
writer.WriteLine(line);
}
}
That, of course, depends on the predicate shouldInsert, but you can modify that as you see so fit. But the nature of IEnumerable<T> should make that relatively light on resources. You could also use a StreamReader for a bit lower-level of support.
using (var writer = new StreamWriter(newFile))
using (var reader = new StreamReader(oldFile))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (shouldInsert(line))
writer.WriteLine(line);
}
}
Recall, of course, that this could leave you with an extra, empty line at the end of the file. I'm too tired to say that with the certainty I should be able to, but I'm pretty sure that's the case. Just keep an eye out for that, if it really matters. Of course, it normally won't.
That all said, the best way to do it would be to have a bit of fun and do it without wasting the memory, by writing a function to read the FileStream in and write out the appropriate bytes to your new file. That's, of course, the most complicated and likely over-kill way, but it'd be a fun undertaking.
See: Append lines to a file using a StreamWriter
Add true to the StreamWriter constructor to set it to "Append" mode. Note that this adds a line at the bottom of the document, so you may have to fiddle a bit to insert or overwrite it at the top instead.
And see: Edit a specific Line of a Text File in C#
Apparently, it's not that easy to just insert or overwrite a single line and the usual method is just to copy all lines while replacing the one you want and writing every line back to the file.
I'm trying to select a set of lines and process each line separately in a text document using c# language. How can i get separate lines to process?
I tried these codes and got struck. Can anyone please help me with this?
EnvDTE.DTE dte = MyPackage.MyPackagePackage.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
EnvDTE.TextSelection text = (dte.ActiveDocument.Selection as EnvDTE.TextSelection);
TextSelection interface has got Text property which you can use as string in C#. Further you can split the string to retrieve the lines.
Alternatively TextSelection interface has additional property called TextRanges which has numeric indexers to access each line.
Have a look at this Link form MSDN.
You can use Startpoint and EndPoint for your job.
Also this Link link might be useful to Loop through all the lines from your selection.
If you are reading from a text file this code will help you:
string fileToRead = "D:\\temp.txt"; // Temp.txt is the file to read
if (File.Exists(fileToRead))
{
StreamReader reader = new StreamReader(fileToRead);
do
{
textBox1.Text += reader.ReadLine() + "\r\n"; // Read each line and pass it to the TextBox1
} while (reader.Peek() != -1);
reader.Close(); // Close the file
}
I want to append lines to my file. I am using code:
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final);
sw.Dispose();
at the moment it's outputting everything in a row.
Use sw.WriteLine(the_final); or sw.Write(the_final + "\n");
But much cleaner:
System.IO.File.AppendAllText("gamedata.txt", the_final + Environment.NewLine);
You should use writeline for writing in a new line sw.WriteLine(the_final)
It Writes a line terminator to the text stream
http://msdn.microsoft.com/en-us/library/ebb1kw70.aspx
You can use the WriteLine() method instead of Write().
I think the issue is when you're constructing your output into the variable: the_final
You need to insert new lines. You can do this by something along these lines:
the_final = "My First Line" + "\r\n";
the_final += "My Second Line!" + "\r\n";
thirdline = "My Third Line!";
the_final += thirdline + "\r\n";
The "\r\n" will produce the carriage return you're looking for.
The other suggestions everyone is making will only append 1 new line to the end of your output, leaving the rest on a single line still.
sw.Writeline(); writes a new line at the end.
sw.Write(); does not append a new line at the end.
Use sw.WriteLine() over Write()
MSDN:
Writes a line terminator to the text stream.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx
Add a newline character manually
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final + "\n");
sw.Dispose();
or use the writeline method
This question is easily answered by a short google search.It's good form to do a bit of research prior to posting
While everyone else has pretty much answered your initial question, may I also suggest this improvement?
using(StreamWriter sw = new StreamWriter("gamedata.txt", true))
{
sw.WriteLine(the_final);
}
When you have an object that inherits from IDisposable, it's good form to use using instead of disposing it manually. For one thing, using will dispose your object even if an exception is encountered.
Using documentation
I have the following code:
void AppendText(string txt)
{
txt = txt + "\r\n";
Textbox1.AppendText(txt);
Textbox1.Select(Textbox1.Text.Length,0);
}
//....
void someFunction()
{
//...
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(Textbox1.Text);
}
}
//...
}
The problem is in Textbox1.Text field in the form, "\r\n" works fine, but when I copy the Textbox1.Text to log.txt, the log.txt doesn't have new line where it's supposed to be. Instead there's a strange charater like this "[]" where "\r\n" is. I think problem lies in the sw.Write(tbox.text) right? But I don't know how to fix it. Could anyone give me a hand? Help is really appreciated. Thanks in advance.
My guess would be that the Textbox creates unicode characters (two bytes per character).
In what format are you reading the data? ASCII unicode UTF?
If I remember correctly /n/r is an old trick to write a newline character to the string but in what format and what does it mean? Environment.Newline is much better and would work on windows mobile/unix builds too.
I usually create a class level variable called br with environment.newline as its content, creates much shorter code.
You should do like this.
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach(string line in Textbox1.Lines)
sw.Write(line+sw.NewLine);
}
}
Your code is correct. Just add sw.Close(); after sw.Write(Textbox1.Text);