Text file doesn't get saved but no errors (C#) - c#

I've been looking on many websites now for the answer, but all working answers only work for the richTextbox, and I'm using the normal textbox. I'm trying to save the contents of the textbox to a file of choice, but for some reason the file doesn't get saved, and I have no idea what the problem is. This is the code of the 'save' menu item:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
//I don't know what to make of this, because clearly this doesn't work
File.WriteAllText(#"./TestFile.txt", MainTextbox.Text);
}
catch (Exception ex)
{
MainTextbox.Text += ex;
}
}
}
There is no error.

You should be saving to the file selected in your SaveFileDialog, as retrieved by OpenFile(). This example worked for me:
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
using (var fileStream = ofd.OpenFile())
using (var sw = new StreamWriter(fileStream))
sw.WriteLine("Some text");
}
In your code, you let the user select a file to save to, then ignore that and write it to a hardcoded location. It's possible your app didn't have permissions to do this, but it should have permissions to write to a location the user selected.

First off, saving the file has nothing to do with where the text is coming from, rich text box or normal text box.
As Brian S. said in a comment, it is likely there is an exception because you're writing to the C drive. You should use a relative path: "./MyTest.txt"

I think its access denied issue.. try with 'D' drive ...
This is working example.. .WriteAllText works when file already exists and if file already exists then use AppendAllText
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}

Use a try { } catch (Exception ex) { } block How to: Use the Try/Catch Block to Catch Exceptions

Related

Copying text from one file into another results in a path denied exception

it says that the path to the file is denied.
looked for an hour no real answers.
please help.
private void btnSetText_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.InitialDirectory = Application.StartupPath;
dlg.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*"; //https://stackoverflow.com/questions/48151581/system-argumentexception-filter-string-not-valid
if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtSetText.Text = dlg.FileName;
}
}
System.IO.File.WriteAllText(txtSetText.Text , text);
every thing is fine and valid, but at the line:
System.IO.File.WriteAllText(txtSetText.Text , text);
I keep getting access to path xyz is denied. How do I make it accessable?
You need to ensure that your destination file is not opened by another program and you need to be sure that your program user have the rights to open and edit this file.

button click which makes attachment dialog open

hey guys I am trying to send an attachment file but the attachment dialog is not opening
but instead it is rather telling me 'input string was not in a correct formart
private void proto_Type_AI_Blackhead_God(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog attachment = new OpenFileDialog();
attachment.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
attachment.Filter = "xml File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif;|Pdf files|*.pdf;|Xml files|*.xml";
if (attachment.ShowDialog() == DialogResult.Value)
{
filename = attachment.FileName;
filename = attachment.SafeFileName;
}
else
{
MessageBox.Show("seriously bad");
}
attachment = null;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm surprised that you got this code compiled.
First of all, OpenFileDialog.ShowDialog() returns bool?, so have it properly checked (for HasValue initally and then the value of Value).
Then, why do you overwrite filename variable? I assume filename is some global variable here.
Further, having that fixed I had no problems running the code, filter string is perfectly correct semantically. Logically, jpegs, bmps and gifs are not XML files.

Unable to automatically save a file after reading it in. c#

I am attempting to create a note taking application (first Windows Forms application). So far I have managed to read a .txt file into a RichTextBox. I am trying to make the program create and save the .txt file containing the contents of the .txt file that was read in read in. So when the user adds text from a file it creates a new file in a notes folders that is in the root directory of application. Please see my code below. Any advice would be greatly appreciated. Cheers
private void button1_Click(object sender, EventArgs e)
{
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = op.FileName;
//create new .txt file contaning module notes
System.IO.StreamWriter file = new System.IO.StreamWriter("\\"+fileName);
file.WriteLine(fileName);
file.Close();
}
Tested and working
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = Path.Combine(Application.CommonAppDataPath, Path.GetFileName(op.FileName));
File.WriteAllText(fileName, "test");
wrap your streams, files (anything that implements IDisposable) in a using block:
using(var myfile = File. CreateText(path) ) {
myfile.WriteLine("hi");
}
it's not creating a file because the path is wrong

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

Save text from rich text box with C#

This question has been answered. I've improved the code a bit (at least I think so). It now reminds of the aceepted answer to the question Open file in rich text box with C#. If I haven't made any mistakes (which I may have), the code should save a file with text from the rich text box rtfMain. The default file extension is .txt. You can also use the file extension .rtf.
private void menuFileSave_Click(object sender, EventArgs e)
{
// Create a new SaveFileDialog object
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
// Default file extension
dlgSave.DefaultExt = "txt";
// SaveFileDialog title
dlgSave.Title = "Save File As";
// Available file extensions
dlgSave.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
// Show SaveFileDialog box and save file
if (dlgSave.ShowDialog() == DialogResult.OK)
{
// Save as .txt file
if (Path.GetExtension(dlgSave.FileName) == ".txt")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
// Save as .rtf file
if (Path.GetExtension(dlgSave.FileName) == ".rtf")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
}
private void rtfMain_TextChanged(object sender, EventArgs e)
{
}
Update: I have improved the code even further (at least I think so). The main difference is that you now have more control over the file encoding. This is the code I'm using right now:
private void fileSave_Click(object sender, EventArgs e)
{
// Text from the rich textbox rtfMain
string str = rtfMain.Text;
// Create a new SaveFileDialog object
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
// Available file extensions
dlgSave.Filter = "All Files (*.*)|*.*";
// SaveFileDialog title
dlgSave.Title = "Save";
// Show SaveFileDialog
if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
{
// Save file as utf8 without byte order mark (BOM)
// ref: http://msdn.microsoft.com/en-us/library/s064f8w2.aspx
UTF8Encoding utf8 = new UTF8Encoding();
StreamWriter sw = new StreamWriter(dlgSave.FileName, false, utf8);
sw.Write(str);
sw.Close();
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
Like this:
rtfMain.SaveFile(dlgSave.FileName);
Your code here saves .doc files formatted. When I use it to save .docx files it does save it but when I try to open the saved file using Microsoft Word, An error message is displayed.

Categories

Resources