I already have the saving part down and I know it works, but when I click load button, it will not display anything that I have saved from the text boxes that go to the saying.txt file
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Grades : Form
{
private StreamWriter fil;
public Grades()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
fil = new StreamWriter("saying.txt"); //This is the txt file
}
catch (DirectoryNotFoundException exc)
{
lstBxDisplay.Text = "Nothing " +
exc.Message;
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
// saving the files to the saying.txt
private void btnSaveAs_Click(object sender, EventArgs e)
{
try
{
fil.WriteLine(txtBxLastName.Text);
txtBxLastName.Text = "";
txtBxLastName.Focus();
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
// next is the load button to load the files into the list/display box
private void btnLoad_Click(object sender, EventArgs e)
{
string inValue;
try
{
using (StreamReader infil =
new StreamReader("saying.txt"))
{
inValue = infil.ReadLine();
while (inValue != null)
{
inValue = infil.ReadLine();
if (inValue != null)
this.lstBxDisplay.Items.Add(inValue);
} // end of while
} // end of using
}
catch (System.IO.IOException exc)
{
lstBxDisplay.Text = exc.Message;
}
}
private void Grades_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
fil.Close();
}
catch
{
}
}
}
}
any reason why it is not loading into the list box? I have tried both label and text box to display the message and neither of them work. I debugged the program and it is executing fine
You have multiple issues here but I will point out two main issues that will get your code working.
You are not closing the stream when you try to save. If the stream stays open, you will never be able to read the values when you try to "Load" the file. You need to call fil.Close(); at the end of your btnSaveAs_Click method.
This is how the save should read.
fil.WriteLine(txtBxLastName.Text);
txtBxLastName.Text = "";
txtBxLastName.Focus();
fil.Close();
You're skipping the first line of the file in your "Load" method. You call infil.ReadLine(); then in the loop, you call it again before you add it to your listbox. You need to move your second ReadLine(). If you are only ever writing a single line to the file, your existing code will skip that first line and try to read it again which will be null (no second line). So, it will never add anything to your listbox.
This is how the reads should be ordered.
using (StreamReader infil = new StreamReader("saying.txt"))
{
inValue = infil.ReadLine();
while (inValue != null)
{
this.lstBxDisplay.Items.Add(inValue);
inValue = infil.ReadLine();
} // end of while
} // end of using
Those changes will get you working. Now to point out, you are going about reading and writing to a file all wrong. You should not be opening a stream in your form load and waiting for button clicks to be writing/reading from that stream. Unless you have a very good reason to do what you are doing, you should be opening your stream, performing the read/write operation, and closing your stream right away. For a simple file IO, I would even suggest using a different mechanism. Look at the MSDN for the System.IO.File Class for easier methods to read lines or write lines to a file.
Related
I have a problem that I wrote an application that would iterate through files and add +1 to the integer each file, until it reaches a specific file name. The problem is probably because .Net does not access the native file system directly, it fills up collections, but in my case it would take years, believe me, I have 260 000 files in the target folder. The iteration does not even reach the second file. The thread just totally freezes, no errors, no exceptions. So is there any way to get a direct access to the Native File System without any useless collection filling ups?
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
try
{
foreach (string file in Directory.GetFiles("\\\\Mypcname-PC\\vxheaven\\malware"))
{
count++;
label1.Text = Convert.ToString(count);
if (file.Contains(textBox1.Text))
{
label1.Text = Convert.ToString(count) + " reached the file";
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
btw. Sorry for my bad english
Regards
Because you are doing all the work on the UI thread it can't refresh while it is working. You need to do the work on a background thread then update the UI in a thread safe way. Also switching to Directory.EnumerateFiles will make it faster to read the first file so it does not need to store all the records in to an array. Lastly I changed ex.Message to ex.ToString(), it will display much more useful information that way.
private async void button1_Click(object sender, EventArgs e)
{
try
{
var text = textBox1.Text;
var progress = new Progress<string>((x) => label1.Text = x);
await Task.Run(() => DoWork(progress, text));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void DoWork(IProgress<string> progress, string text)
{
foreach (string file in Directory.EnumerateFiles("\\\\Mypcname-PC\\vxheaven\\malware"))
{
count++;
progress.Report(Convert.ToString(count));
if (file.Contains(text))
{
progress.Report(Convert.ToString(count) + " reached the file");
break;
}
}
}
(Code was written in a web browser from memory so there may be errors)
Seems like you are using a potentially very time-consuming loop without ever processing the Windows message queue, therefore your application may APPEAR to be frozen, while it's probably just busy doing what you instructed it to do in the loop. Try this:
private void button1_Click(object sender, EventArgs e)
{
try
{
foreach (string file in Directory.GetFiles("\\\\Mypcname-PC\\vxheaven\\malware"))
{
count++;
label1.Text = Convert.ToString(count);
Application.DoEvents();
if (file.Contains(textBox1.Text))
{
label1.Text = Convert.ToString(count) + " reached the file";
break;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm building a program that has you input a number and remembers it when you re-open the program. It uses a text file to save the number in. I'm using streamreader to read the text file to get the number you entered last, but it always throws an exception. Where should I put the text file or change my code so it can read and edit the text? Here is my code:
namespace Cookie_Clicker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void tb_TextBox(object sender, RoutedEventArgs e)
{
}
private void add_Click(object sender, RoutedEventArgs e)
{
try
{
using (StreamReader sr = new StreamReader("cookies.txt"))
{
int data = Convert.ToInt16(sr.ReadToEnd());
tb.Text = Convert.ToString(data + 1);
}
}
catch (Exception)
{
MessageBox.Show("Your cookie text file is missing!");
}
}
private void reset_Click(object sender, RoutedEventArgs e)
{
}
}
}
Every time it says "Your cookie text file is missing!"
Problem 1: You are not specifying proper path of your input file.
Solution 1: You need to get the Currentpath of your application from where it is running and then combine it with the filename using Path.Combine() method.
Try This:
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cookies.txt");
using (StreamReader sr = new StreamReader(path))
{
int data = Convert.ToInt16(sr.ReadToEnd());
tb.Text = Convert.ToString(data + 1);
}
Suggestion : You need to always display the Error message in Catch block to identify the problem.
You can call ToString() on Exception object to get the complete exception info.
catch (Exception ex)
{
MessageBox.Show(ex.ToSTring();
}
To answer your question:
Where should I put the text file...?
You haven't specified a path to cookies.txt so the program will look for it in the same directory where it's running. If you change cookies.txt to include a path, for example C:\dev\cookies.txt, then you can store the file wherever you like.
That will allow you to get past the file not found error and address any other problems you have in there.
I'm working on a wp8-app that takes a photo and then takes you to the next screen to decide whether you like it or not.
The current approach was this:
private void ShutterButton_Click(object sender, RoutedEventArgs e)
{
if (cam != null)
{
try
{
cam.CaptureImage();
await Task.Delay(1500);
NavigateFront();
}
catch (Exception ex)
{
...
}
}
}
public void NavigateFront()
{
string naviString = "/confirmPicture.xaml?parameter=" + fileName.ToString();
_rootFrame.Navigate(new Uri(naviString, UriKind.Relative));
}
On my Lumia 520 it crashed sometimes. If I increase the wait-time to 2,5sec it works. But of course this should not be the way to do it.
If I catch the void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)-Event and try to navigate after everything is done and all streams are closed I still get in a NavigateFailed-State and the app crashes.
My question is: is there any other useful event that ensures that all work is done and I can navigate without using static time-based values?
Navigation with a PhotoCamera is possible, just subscribe to its CaptureCompleted event handler
cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
and this would be the event
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
Deployment.Current.Dispatcher.BeginInvoke(delegate()
{
try
{
cam.Dispose();
NavigationService.Navigate(new Uri("URI nething", UriKind.Relative));
}
catch (Exception)
{
MessageBox.Show("Problem occured!!");
}
});
}
catch
{
MessageBox.Show("Problem in camer_capturecompleted");
}
}
I did it in one of my apps targeting windows phone 7. Check if this works for you as well.
I have an application where I load an image dynamically. Let's say, that image doesn't exists and we want to notify the user and then exit. In my main loop, I have exception handling which works just fine when I'm reading files with StreamReader. However, if I am throwing exception from another function, the app just crashes and in the error report I see thrown exception (IOException). To get an idea of the app:
public MainWindow()
{
try {
InitializeComponent();
Load(myFile);
} catch (IOException e) {
MessageBox.Show("Opening failure.");
Application.Current.Shutdown();
}
}
public void Load(string imgPath)
{
string tmpStr;
string[] tmp;
using (StreamReader sr = new StreamReader("myFile.txt", System.Text.Encoding.Default)) {
while ((tmpStr = sr.ReadLine()) != null) {
tmp = tmpStr.Split(' ');
...
}
}
}
private void Grid_Click(object sender, RoutedEventArgs e)
{
...
if (!File.Exists(myFile)) {
throw new IOException("File doesnt exist");
}
...
}
BUT, if I put try-catch block inside Grid_Click, it catches that exception.
The exception that is thrown in Grid-Click would not be caught by the catch statement in the MainWindow() method by design, since the method call to Grid_Click is not inside that try block.
The Grid_Click method is called when the click event is fired, which is at an asynchronous time. Only IOExceptions thrown inside the try block in MainWindow will be caught by that catch statement you have listed above.
What you call 'main loop' is just a constructor. The code does not execute under it's control.
I'm developing an application that has a TextBox. I want to write its contents to a file, but how can I do this?
There are many ways to accomplish this, the simplest being:
using(var stream = File.CreateText(path))
{
stream.Write(text);
}
Be sure to look at the MSDN page for File.CreateText and StreamWriter.Write.
If you weren't targeting the .NET Compact Framework, as your tags suggest, you could do even simpler:
File.WriteAllText(path, string);
System.IO.File.WriteAllText("myfile.txt", textBox.Text);
If you're stuck on some brain-dead version of the BCL, then you can write that function yourself:
static void WriteAllText(string path, string txt) {
var bytes = Encoding.UTF8.GetBytes(txt);
using (var f = File.OpenWrite(path)) {
f.Write(bytes, 0, bytes.Length);
}
}
Try this:
using System.Text;
using System.IO;
static void Main(string[] args)
{
// replace string with your file path and name file.
using (StreamWriter sw = new StreamWriter("line.txt"))
{
sw.WriteLine(MyTextBox.Text);
}
}
Of course, add exception handling etc.
For a richTextBox, you can add a "Save" button for this purpose. Also add a saveFileDialog control from Toolbox, then add following code in button's click event.
private void button1_Click(object sender, EventArgs e)
{
DialogResult Result = saveFileDialog1.ShowDialog();//Show the dialog to save the file.
//Test result and determine whether the user selected a file name from the saveFileDialog.
if ((Result == DialogResult.OK) && (saveFileDialog1.FileName.Length > 0))
{
//Save the contents of the richTextBox into the file.
richTextBox1.SaveFile(saveFileDialog1.FileName);
}
}