Streamreader to display - c#

I'm still on my first step on C# and this is my first post/question.
How do I implement Streamreader to Display(output)
Like after clicking the Dataretrieve button I want to retrieve the data located on "D:\Savedata.txt" and display it on the lblDisplay
This is my code, am I missing something?
void DataretrieveClick(object sender, EventArgs e)
{
StreamReader read = File.OpenText("D:\\Savedata.txt");
lblDisplay.Text = "Last Name: " +textBox1.Text.Trim();
read.Close();
}

Something like this should be what you're looking for.
void DataretrieveClick(object sender, EventArgs e)
{
using (StreamReader reader = File.OpenText("D:\\Savedata.txt"))
{
lblDisplay.Text = reader.ReadToEnd();
}
}
When you create an instance of a class that implements interface IDisposable, you should wrap it in a using() statement to make sure the resources for it are freed when you leave the using() scope. Also, you can look over the documentation for StreamReader here which should help you see what's available.

There is very handy static method ReadAllText in File class, which will open a text file, read all lines of the file, and then close the file:
lblDisplay.Text = File.ReadAllText("D:\\Savedata.txt");
Internally this method does exactly what you are trying to implement (creates StreamReader and reads all characters from the current position to the end of the stream):
using (var reader = new StreamReader(path, Encoding.UTF8, true, 0x400, true))
{
return reader.ReadToEnd();
}

You're looking for read.ReadToEnd().

Related

c# override streamreader but can I close and reopen it?

I'm merging some of my cvs reading code into a single class, and I'm thinking of just making it override streamreader. However, I want to keep the class private values I added (delimiter, recordcount, etc) and be able to close and reopen the file.
The reason I need to be able to is to do a quick pass to determine various things such as the delimiter, whether there are embedded line breaks in the data, actual record count, field count, etc.
Obviously I can't use using (streamreader sr = new streamreadder(filename)) because that will destroy the object at the end but can I close the file and reopen it? Can I do cvsstreamclass sr = new cvsstreamclass(filename), and then sr.close() and sr.open()? I understand that streamreader seek has problems so I probably shouldn't just use that.
Or am I going about this all wrong and should I just pass in the streamreader object to a class that handles the parsing and whatnot??
btw, I'm not looking at switching to an opensource cvs class or other library. I've already got a lot of this code written, and it works. No need to suggest that.
A CSV parser is not a StreamReader. The two are not related and there should not be an inheritance relationship.
Your CsvReader class should have a StreamReader member. You can the set and manipulate that member however you like. For example, you can close the existing reader and create a new one at any time.
I recommend you actually store the StreamReader in your reader class. There is no point in subclassing StreamReader unless you're going to expose it to some other code in the form of a StreamReader. I would do something like this:
public class CSVReader
{
private StreamReader reader;
private string fileName;
//Your other properties and fields here
public CSVSReader(string filename)
{
this.fileName = fileName;
InitReader();
}
public void CloseFile()
{
if (reader != null)
{
reader.Close();
reader = null;
}
}
public void OpenFile()
{
CloseFile();
reader = new StreamReader(File.OpenRead(fileName));
}
//Your other methods here
}
Obviously, I'm not using any try-catch blocks for opening the file, but that's just for the sake of readability.
You could also inherit from IDisposable, making your class usable inside a using () block.

Append input into text file instead of replacing it

I'm trying to take the data from two text boxes, and writing it to file without replacing the current stuff already there when a button is pressed. This is what I have so far:
private void button1_Click_1(object sender, EventArgs e)
{
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
}
Right now it takes the input, and replaces whatever is currently in the files so then there is only one line, instead of just adding it to the list. Thanks for the help.
//using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
//{
// sw1.WriteLine(textBox1.Text);
//}
System.IO.File.AppendAllText("DataNames.txt", textBox1.Text);
Use StreamWriter Constructor (String, Boolean) constructor and pass true for append.
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and
the constructor creates a new file.
In your code pass true like:
using (StreamWriter sw1 = new StreamWriter("DataNames.txt",true))
Try this
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt", true))
{
sw2.WriteLine(textBox2.Text);
}
Second argument true tells that file needs to be appended instead of overwriting. StreamWriter(String, Boolean)
Switch the
new StreamWriter("DataNumbers.txt")
to
File.CreateText("DataNames.txt")
You can find more info at:
http://msdn.microsoft.com/en-us/library/system.io.file.appendtext.aspx
You are making two separate instance of stream writer, and they are both attempting to write to the same file, so they are competing with each other - that's why you are seeing the overwriting.
If you want to add text to the end of a file, the best way to do so is probably File.AppendAllText: http://msdn.microsoft.com/en-us/library/ms143356.aspx
private void button1_Click_1(object sender, EventArgs e)
{
System.IO.File.AppendAllText("DataNames.txt", textBox1.Text + textBox2.Text);
}
AppendAllText is quite useful if you are doing small, relatively infrequent appends as you can just send strings into it without thinking as opposed to making sure you are using your stream writer.

How to retrieve large strings over TCP using Streamreader

I'm trying to receive large strings over TCP, I tried various methods, but none of them worked as good as this one (which is quite simple actually).
public partial class MyClass : Form
{
Int64 counter;
StreamWriter writer;
StreamReader reader;
public MyClass(object streamIn, object StreamOut)
{
InitializeComponent();
richTextBox1.BackColor = Color.Black;
richTextBox1.ForeColor = Color.Gray;
writer = (StreamWriter)streamIn;
reader = (StreamReader)StreamOut;
}
private void button1_Click(object sender, EventArgs e)
{
JObject o = new JObject();
char[] buffer = new char[1024];
int count = buffer.Length;
o.Add("comando", 15);
o.Add("filename", textBox2.Text);
o.Add("param", textBox3.Text);
writer.Write(o.ToString());
writer.Flush();
richTextBox1.Text = reader.ReadToEnd();
}
}
The problem using this is that I have to close the stream on the other end, in order for this to read. There is any way I can use reader.ReadToEnd() without having to close the stream on the other end after sending and therefore closing the connection between client-server?
Checkout the Basic Example for the network library networkcomms.net which is covered in the Getting Started article. Although this is a console example it allows you to send arbitrary length strings.
Your example looks like it might be a winform application. There is also a WPF chat application example if that is of interest.

Writing data from textbox into text file

Here is the code im using to write and read from text file.
StreamWriter sw1 = new StreamWriter("DataNames.txt");
sw1.WriteLine(textBox1.Text);
sw1.Close();
StreamWriter sw2 = new StreamWriter("DataNumbers.txt");
sw2.WriteLine(textBox2.Text);
sw2.Close();
FileInfo file1 = new FileInfo("DataNames.txt");
StreamReader sr1 = file1.OpenText();
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
The thing is that when I click my button to save data from my textboxes to my text files an error appears that says "The process cannot access the file 'C:\xxxx\xxxxxx\xxxxx\xxxx\xxxxx\xxxxx.txt' because it is being used by another process."
Can anyone tell me why I have this error and maybe help me fix it
Try added a using statment around your streams to make sure they are Disposed otherwise the file is still locked to the stream
Example:
//Write
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
// Read
foreach (var line in File.ReadAllLines("DataNames.txt"))
{
listBox1.Items.Add(line);
}
foreach (var line in File.ReadAllLines("DataNumbers.txt"))
{
listBox2.Items.Add(line);
}
It appears you do not close the file after you read it. After you call FileInfo.OpenText you get a StreamReader which has to be closed, either via Close method, or even better, with a using statement.
But there are already methods that do all that for you, have a look at File.WriteAllText,
File.AppendAllText and File.ReadAllLines methods.
You need to Close the StreamReader object once you do not need it any more. This should fix this issue.
I.e.
StreamReader sr1 = file1.OpenText();
try {
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
}
finally {
sr1.Close();
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
try {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
finally {
sr2.Close();
}
You have opened files but not closed.
StreamReader sr1 = file1.OpenText();
StreamReader sr2 = file2.OpenText();
Your problem occurs, because you are not closing the stream readers.
A safer way of using external resources (the files in this case) is to embed their use in a using statement. The using statement automatically closes the resource at the end of the statement block or if the statement block if left in another way. This could be a return statement or an exception, for instance. It is guaranteed that the resource will be closed, even after an exception occurs.
You can apply the using statement on any object which implements the IDisposable interface.
// Writing to the files
using (var sw1 = new StreamWriter("DataNames.txt")) {
sw1.WriteLine(textBox1.Text);
}
using(var sw2 = new StreamWriter("DataNumbers.txt")) {
sw2.WriteLine(textBox2.Text);
}
// Reading from the files
FileInfo file1 = new FileInfo("DataNames.txt");
using (StreamReader sr1 = file1.OpenText()) {
while (!sr1.EndOfStream) {
listBox1.Items.Add(sr1.ReadLine());
}
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
using (StreamReader sr2 = file2.OpenText()) {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
However, you can simplify the reading part like this
// Reading from the files
listBox1.Items.AddRange(File.ReadAllLines("DataNames.txt"));
listBox2.Items.AddRange(File.ReadAllLines("DataNumbers.txt"));
I've seen this behavior before - usually there's another process open that's blocking the file access. Do you have multiple development servers open in your taskbar? (Strange, yes, but I've seen it happen)

Write data from Textbox into text file in ASP.net with C#

I have a textbox where a user can input their email, what I want to do is make it so that when they click a submit button. That email will be saved into a text file ( on my server ) called emails.txt
I managed to get this working using System.IO and then using the File.WriteAll method. However I want to make it so that it will add the email to the list ( on a new line ) rather then just overwriting whats already in there.
I've seen people mention using Append, but I can't quite grasp how to get it working.
This is my current code (that overwrites instead of appending).
public partial class _Default : Page
{
private string path = null;
protected void Page_Load(object sender, EventArgs e)
{
path = Server.MapPath("~/emails.txt");
}
protected void emailButton_Click(object sender, EventArgs e)
{
File.WriteAllText(path, emailTextBox.Text.Trim());
confirmEmailLabel.Text = "Thank you for subscribing";
}
}
You can use StreamWriter to get working with text file. The WriteLine method in true mode append your email in new line each time....
using (StreamWriter writer = new StreamWriter("email.txt", true)) //// true to append data to the file
{
writer.WriteLine("your_data");
}
From the official MSDN documentation:
using (StreamWriter w = File.AppendText("log.txt"))
{
MyWriteFunction("Test1", w);
MyWriteFunction("Test2", w);
}
Use StreamWriter in Append mode. Write your data with WriteLine(data).
using (StreamWriter writer = new StreamWriter("emails.txt", true))
{
writer.WriteLine(email);
}
Seems like a very easy question with a very easy answer: Open existing file, append a single line
If you post the current code, we can modify that to append instead of overwrite.

Categories