I'm trying to make a simple Windows Form Application that saves a text file. I'm having trouble with the following program, it gives me:
Empty path is not a legal
namespace Filing
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button_Save_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.Filter = "Text (*.txt) | Word File *.doc";
file.Title = "Save a file";
File.WriteAllText(file.FileName, richTextBox1.Text);
file.ShowDialog();
}
private void button_exit_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Cause you didn't "show" the SaveFileDialog yet, so the fileName is empty.
Try moving the showDialog upward:
private void button_Save_Click(object sender, EventArgs e)
{
SaveFileDialog file = new SaveFileDialog();
file.Filter = "Text (*.txt) | Word File *.doc";
file.Title = "Save a file";
//Ask the user to select the file path and file name, don't forget to handle cancel button!
if(file.ShowDialog() != DialogResult.Cancel)
{
File.WriteAllText(file.FileName, richTextBox1.Text);
}
}
You should wrap the writing statement as the following.
if(file.ShowDialog()== DialogResult.OK)
File.WriteAllText(file.FileName, richTextBox1.Text);
Related
I am creating an app that i need to copy some png files.
I already have searching with many keywords, finding many solutions and none of them worked, so i decided to ask here.
There is the code,it uses a windows forms and "this" refers to this window
private void button2_Click(object sender, EventArgs e)
{
//yes i commented them to solve why the file was not copying
//try
{
FileInfo x = new FileInfo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\some_location");
x.CopyTo(textBox1.Text);
}
//catch
{ }
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Title = "Select Image To Load";
openDialog.Filter = "Text Files (*.png)|*.png" + "|" + "All Files (*.*)|*.*";
if (openDialog.ShowDialog() == DialogResult.OK)
{
string PathData = openDialog.FileName;
textBox1.Text = PathData;
}
}
I have gotten several different errors, but most common there is:
System.UnauthorizedAccessException
It looks a bit weird to me that you're using an OpenFileDialog to select a destination. I'd assume you'd want to either do it the other way around:
private void button2_Click(object sender, EventArgs e)
{
//yes i commented them to solve why the file was not copying
//try
{
FileInfo x = new FileInfo(textBox1.Text);
x.CopyTo(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + #"\some_location");
}
//catch
{ }
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openDialog = new OpenFileDialog();
openDialog.Title = "Select Image To Load";
openDialog.Filter = "Text Files (*.png)|*.png" + "|" + "All Files (*.*)|*.*";
if (openDialog.ShowDialog() == DialogResult.OK)
{
string PathData = openDialog.FileName;
textBox1.Text = PathData;
}
}
or use SaveFileDialog instead.
I am not able to save content of a text file while using the save option in notepad in visual c#
The code I have used is:-
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string s = richTextBox1.Text;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName,RichTextBoxStreamType.RichText);
}
}
You need to use RichTextBoxStreamType.PlainText
Hence code should be -
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string s = richTextBox1.Text;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(saveFileDialog1.FileName,RichTextBoxStreamType.PlainText);
}
}
I created an app for my dad. It's just a simple dictation program. The thing is when he installed it on his computer it stalled and said the general access denied error.
The first time it gave the error I used SaveFileDialog sfd = new SaveFileDialog() then added the usually 'if statement" to make sure the dialog was ok. However the app had an access file denied.
I did the same thing with Environment.GetFolder and it installed on his computer to the location and ran fine. However, when I use the saveFileDialog1 and openFileDialog1 out of the tool box it does not save or open a txt document.
It works on my laptop and not his. Could this be due to an error in the code vs his computer. Also what is the correct way to use the Environement.GetFolder with the SaveFileDialog.
I can also post the full code to the program if needed.
private void lblOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Title = "Open File";
open.Filter = "Text Files (*txt) | *.txt";
if (open.ShowDialog() == DialogResult.OK)
{
StreamReader read = new StreamReader(File.OpenRead(open.FileName));
txtTextBox.Text = read.ReadToEnd();
read.Dispose();
}
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
This is the Enviroment i used on my screen recorder. i when i click save it brings up a dialog box i put in the file name press save and it does nothing. It saves the file but not as i specified. So i am trying to merge the above and below codes. The above code does not grant access however the below does
string OutputPath;
OutputPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + #"\\IvanSoft Desktop Recorder" + saveFileDialog1;
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string fileName = saveFileDialog1.FileName;
fileName = "Tutorial";
}
the whole code to the program
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Threading;
namespace AGM_Speech
{
public partial class Form1 : Form
{
public SpeechRecognitionEngine recognizer;
public Grammar grammar;
public Thread RecThread;
public Boolean RecognizerState = true;
public Form1()
{
InitializeComponent();
}
private void lblAbout_Click(object sender, EventArgs e)
{
this.Hide();
About about = new About();
about.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
GrammarBuilder builder = new GrammarBuilder();
builder.AppendDictation();
grammar = new Grammar(builder);
recognizer = new SpeechRecognitionEngine();
recognizer.LoadGrammarAsync(grammar);
recognizer.SetInputToDefaultAudioDevice();
recognizer.SpeechRecognized += new EventHandler<SpeechRecognizedEventArgs>(recognizer_SpeechRecognized);
RecognizerState = true;
RecThread = new Thread(new ThreadStart(RecThreadFunction));
RecThread.Start();
}
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if (!RecognizerState)
return;
this.Invoke((MethodInvoker)delegate
{
txtTextBox.Text += (e.Result.Text.ToLower() + " ");
txtTextBox.SelectionStart = txtTextBox.Text.Length - 0;
txtTextBox.SelectionLength = 0;
});
}
public void RecThreadFunction()
{
while (true)
{
try
{
recognizer.RecognizeAsync();
}
catch
{
}
}
}
private void lblStartSpeech_Click(object sender, EventArgs e)
{
RecognizerState = true;
}
private void lblStopSpeech_Click(object sender, EventArgs e)
{
RecognizerState = false;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
RecThread.Abort();
RecThread = null;
grammar = null;
recognizer.UnloadAllGrammars();
recognizer.Dispose();
}
private void lblOpenFile_Click(object sender, EventArgs e)
{
string open = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamReader reader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
private void lblSaveFile_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter write = new StreamWriter(File.Create(save.FileName));
write.Write(txtTextBox.Text);
write.Dispose();
}
}
private void txtSearch_Click(object sender, EventArgs e)
{
txtSearch.Clear();
lblGo_Click(null, null);
}
private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)ConsoleKey.Enter)
{
lblGo_Click(null, null);
}
}
private void lblGo_Click(object sender, EventArgs e)
{
int index = 0;
String temp = txtTextBox.Text;
txtTextBox.Text = "";
txtTextBox.Text = temp;
while (index <= txtTextBox.Text.LastIndexOf(txtSearch.Text))
{
txtTextBox.Find(txtSearch.Text, index, txtTextBox.TextLength, RichTextBoxFinds.None);
txtTextBox.SelectionColor = Color.YellowGreen;
index = txtTextBox.Text.IndexOf(txtSearch.Text, index) + 1;
}
}
}
}
It's hard to say where you're failing, because there isn't much in the way of try/catch or logging.
Can you use this instead, and paste the stack trace that shows in the Message Box?
private string fileOutputLocation { get; set; }
private void lblSaveFile_Click(object sender, EventArgs e)
{
bool fileSelected = false;
Try(() =>
{
SaveFileDialog save = new SaveFileDialog();
save.Title = "Save File";
save.Filter = "Text Files (*txt) | *.txt";
save.InitialDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "IvanSoft Desktop Recorder");
if (save.ShowDialog() == DialogResult.OK)
{
fileOutputLocation = save.FileName;
fileSelected = true;
}
});
if (fileSelected)
{
bool fileSaved = SaveFile();
MessageBox.Show("File saved successfully: " + fileSaved.ToString());
}
}
private bool SaveFile()
{
TryDeleteFile();
bool fileSaved = false;
Try(()=>
{
File.WriteAllText(fileOutputLocation, txtTextBox.Text);
fileSaved = true;
});
return fileSaved;
}
private void TryDeleteFile()
{
Try(()=>
{
if (File.Exists(fileOutputLocation))
{
File.Delete(fileOutputLocation);
}
});
}
private void Try(Action action)
{
try
{
action();
}
catch (Exception e)
{
MessageBox.Show(string.Format("The following exception was thrown:\r\n{0}\r\n\r\nFile path: {1}", e.ToString(), fileOutputLocation));
}
}
With this, plus the events logged to the Windows Event Viewer (Start>Run>Eventvwr>Security), we should be able to tell you what the problem is.
Lastly, if you're just providing an executable to run, you should check the properties of the file to ensure it's not blocked in Windows.
I tried to open an xml file with open file dialog and want to removed some duplicate data from the file now my problem is selecting the file and saving that file (load, delete,save buttton on my winforms).can you please where am I going wrong.
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e) // open file dialog works fine
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
{
}
}
}
private void button2_Click(object sender, EventArgs e)//Deleteing duplicate data
{
//var doc = XDocument.Load(#"C:\\Users\IT-Administrator\Desktop\21.xml");/ do i need to use this line.
doc.Root.Elements("Incident")
.GroupBy(s => (string)s.Element("Comment"))
.SelectMany(g => g.Skip(1))
.Remove();
//doc.Save(#"C:\Users\IT-Administrator\Desktop\2014-01-07_Middlesex.xml");
//doc.Save(#"C:\Users\IT-Administrator\Desktop\22.xml");
}
private void button3_Click(object sender, EventArgs e)//saving..
{
//doc.Save(#"C:\Users\IT-Administrator\Desktop\22.xml");
saveFileDialog1.ShowDialog();
}
To save your XML-File you have to:
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML-File | *.xml";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
xDocument.Save(saveFileDialog.FileName);
}
I have a windows form application I have a button that opens the SaveFileFrom dialog
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog savefileDialog1 = new SaveFileDialog();
savefileDialog1.ShowDialog();
}
I was wondering how I could put the file that is chosen in a text box even like so
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
UPDATE* Ok, well since the user might want to open more than one file to save I wanted to take off my button SaveFileFrom and instead make the textbox run through the OpenFileDialog when clicked.
Also, is their a way to make a text link instead of a button?
Like I want a text link to add another text box/
Try this
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog savefileDialog1 = new SaveFileDialog();
if (savefileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = savefileDialog1.Filename;
}
}
The filename selected will be saved in SaveFileDialog.FileName
example:
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog SvDlg = new SaveFileDialog();
if (SvDlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = SvDlg.FileName;
}
else
{
MessageBox.Show("No file selected.");
}
}