Writing Something to a File then loading it again - c#

Okay so i wanted to know how i would take something that is in a textBox, then i press a button, the contents of the textBox will be saved to a file location, then when i load the .exe back up, the contents will reappear in the textBox.
This is what i have so far
private void button3_Click(object sender, EventArgs e)
{
File.WriteAllText(#"C:\Application.txt", textBox1.Text);
}
^To Write it to a file location, I have tried this multiple times but it doesnt seem to want to make the file on my C:.
private void Form1_Load(object sender, EventArgs e)
{
try
{
textBox1.Text = File.ReadAllText(#"C:\Application.txt", Encoding.ASCII);
}
catch
{
}
^To Load the file then inject it back into the textbox it came from
Any and all help is appreciated,
Thanks.

You likely get an exception when trying to write to your C drive because it requires administrative access. Try running Visual Studio as Administrator (therefor the app will run as admin when kicked off from VS) or try writing to another location. Your code is all fine. The Encoding.ASCII bit is unnecessary though and I recommend removing it (more than likely that's not the encoding you will write the file in).

Trying to write directly to the C: drive can cause problems.
Try writing to a location that you definitely have write access to. You could use the ApplicationData directory (for application files unique to the current user), or use SpecialFolder.MyDocuments if you prefer.
private string applicationFilePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "Application.txt");
private void button3_Click(object sender, EventArgs e)
{
File.WriteAllText(applicationFilePath, textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
textBox1.Text = File.ReadAllText(applicationFilePath, Encoding.ASCII);
}

I would do something like this:
using System.IO;
private void button3_Click(object sender, EventArgs e)
{
using (var stream = new FileStream(#"C:\Application.txt", FileMode.Create))
using (var writer = new StreamWriter(stream, Encoding.ASCII))
writer.Write(textBox1.Text);
}
private void Form1_Load(object sender, EventArgs e)
{
using (var stream = new FileStream(#"C:\Application.txt", FileMode.Open))
using (var reader = new StreamReader(stream, Encoding.ASCII))
textBox1.Text = reader.ReadToEnd();
}
I think this method gives you more control on your content. Try to explore the contents of FileMode enum, and make sure to add your using System.IO; directive.
Be careful not to confuse the using statement with the using directive.
Also, always remember to dispose/close your stream when done to ensure that the data has been flushed and that the file is no longer in use by your application. Here, the using statement does the job of disposing when the stream is no longer in use.
EDIT: As mentioned by the other posts, writing to the C: directory causes problems on newer operating systems due to Admininstrative Access restrictions. Make sure to write to different drives/folders that you definitely have access to.
// Current User
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Application.txt");
// All users
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Application.txt");

Related

File.WriteAllText() statement in C# not creating a file

I am still only just learning C# in Visual Studio and I am trying to make a simple text encryption application. My problem at the moment is that when I use the command:
File.WriteAllText(name, inputTextBox.Text);
(Where name is the name of the file chosen in a SaveFileDialog and inputTextBox.Text is the text in a textbox on the main form)
however the file is never actually created. I even tried to build the application and run it as administrator but nothing happened.
What's even weirder is when I opened File Explorer, in the Quick Access section where it shows recent files, all the files that were supposed to be created show up there but don't exist when I click "Open File Location" and if I just try to open them, notepad just tells me the file doesn't exist.
The files are also not in my recycle bin or anything.
Here's the rest of my code in case it's something wrong with that:
public Form1()
{
InitializeComponent();
}
private void saveButton_Click(object sender, EventArgs e)
{
saveDialog.ShowDialog();
}
private void saveDialog_FileOk(object sender, CancelEventArgs e)
{
string name = saveDialog.FileName;
File.WriteAllText(name, inputTextBox.Text);
}
And in case you're wondering saveDialog is already an element in my form so there's no problem with that.
Since in your posted code the initialization of the SaveFileDialog is missing, and you say in your comment that the Debugger doesn't halt in the event body I take the long shot to assume that the event is not registered appropriately.
Try to make sure that your class (minimally) looks like the following example:
public partial class Form1 : Form
{
SaveFileDialog saveDialog;
public Form1()
{
InitializeComponent();
// create instance of SaveFileDialog
saveDialog = new SaveFileDialog();
// registration of the event
saveDialog.FileOk += SaveDialog_FileOk;
}
private void saveButton_Click(object sender, EventArgs e)
{
saveDialog.ShowDialog();
}
private void saveDialog_FileOk(object sender, CancelEventArgs e)
{
string name = saveDialog.FileName;
File.WriteAllText(name, inputTextBox.Text);
}
}
If your problem still remains, then I will remove my answer

C# load video from resources folder not playing

I trying to load my video from the resources folder but its not playing automatically once my form load. Can I know what mistake i have done. Thank you.
This is my c# code:
private void Form2_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = #"Resources/abc.mp4";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
Well I have solved it my ownself. Actually, I accidentally added the # symbol into my url. That causes the problem. This is the updated code.
private void Form2_Load(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = "Resources\\abc.mp4";
axWindowsMediaPlayer1.Ctlcontrols.play();
}
To do that king of thing, you must get the stream of your resource.
So that code should work for you because works for me :)
// temporary file path - your temp file = video.avi
var strTempFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Video.avi");
try
{
// ResourceName = the resource you want to play
File.WriteAllBytes(strTempFile, Properties.Resources.ResourceName);
axWMP.URL = strTempFile;
axWMP.Ctlcontrols.play();
}
catch (Exception ex)
{
// Manage me
}
You can implement a axWMP_PlayStateChange method to remove video.Avi at the end.
Hope it could help you

How to open notepad in c# by button

I am new to programming and stuck on a little thing. I have a button on my Windows application and I want to open Notepad when I click the button. I used all the available codes from internet starting from process.start() to even envirnoment.path but the button doesn't show the Notepad. Here is what I have already tried.
private void btnNotepad_Click(object sender, EventArgs e)
{
string notepadPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.SystemX86), "notepad.exe");
System.Diagnostics.Process.Start(notepadPath);
}
Or simply:
system.diagnostics.process.start(#"notepad.exe");
Also did this:
string theData = txtbxRepeat.Text;
FileStream aFile = new FileStream("myTextFile.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(aFile);
txtbxRepeat.Text = theData;
sw.WriteLine(theData);
sw.Close();
Please help me in this.
You are heading in the correct direction with the first and 2nd code snippet. However, you need to specify the full path to the notepad++ exe.
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Notepad++", #"notepad++.exe"));
}
However, keep in mind the user may have installed notepad++ in a different directory (for example they don't have an x86 directory).
UPDATED: updated to include environment paths rather than hard-coded path.

How to check for a specific file and delete it

i am using a C# winform in which i wanted to search for a particular file in a folder and i want to delete it.
How can i do this. i am trying with the below codes.
private void button4_Click(object sender, EventArgs e)
{
string Filename = img_path.Text; // here i have the filename "sample.grf"
if (Directory.GetFiles(#"E:\Debug").Where(x => x.Name == Filename).Any()) // getting error here
{
// i want to search here in above folder and delete the file.. how to do this
System.IO.File.Delete(/dont know how to delte the particular file);
}
}
please help out
This is simply done this way:
File.Delete(Path.Combine(#"E:\Debug", Filename));
No need to check if the file exists first. If it doesn't, File.Delete will simply do nothing.
If you may have any security concern (like a user entering ..\SomethingElse\Important.doc for instance), you need to ensure the field only contains a file name. One way would be:
if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
return;
So your whole function may look lie this:
private void button4_Click(object sender, EventArgs e)
{
string Filename = img_path.Text;
if (string.IsNullOrEmpty(Filename))
return;
if (Filename.ToCharArray().Intersect(Path.GetInvalidFileNameChars()).Any())
return;
File.Delete(Path.Combine(#"E:\Debug", Filename));
}
Also, button4_Click is not a very friendly name to maintain. You may want to consider renaming the button and that function to something meaningful.
If you know the file, just Delete() it:
File.Delete("C:\\mypath\\myfile.txt");
There is no exception thrown for a file that already does not exist, according to MSDN.

openfile dialog cancel crash

I am making a basic word processor in c# for training. Now I am making the open file part of it. I can open a text file without issue. But when I open the open file dialog and then cancel it, it crashes :/
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
getRichTextBox().Text = OpenFile.ReadToEnd();
}
I know it is because the streamreader has nothing to read but I am not sure how to solve this.
thanks in advance!
Edit: Thank you! it worked perfectly :)
You need to check the result of the dialog:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK) {
using (var openFile = new StreamReader(openFileDialog1.FileName)) {
getRichTextBox().Text = OpenFile.ReadToEnd();
}
}
}
I've also added a using statement to ensure that your file is closed when you're done reading it.
You can simplify the code even further by simply using File.ReadAllText instead of messing around with StreamReader.
getRichTextBox().Text = File.ReadAllText(openFileDialog1.FileName);
(Thanks #keyboardP)
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
getRichTextBox().Text = OpenFile.ReadToEnd();
}

Categories