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.
Related
I'm pretty new to C# and I'm experimenting a lot, I'm trying to make my program a little more user friendly and that is where the problem starts.
At first the location of the excelfile was in a public static string and I had no problems. I've changed it to this:
public string Excellocation()
{
string xlLocation;
if (but_Browse.Text == "Zoek Excel")
{
xlLocation = #"E:\Levi\Documents\Verjaardagen.xlsx";
}
else //Only if I get into this part of my code I get the error
{
xlLocation = but_Browse.Text;
}
return xlLocation;
}
And the button I use so the user can give me a location for the excel file is:
private void but_Browse_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
but_Browse.Text = fileToOpen;
this.but_Browse.AutoSize = true;
But_Import.Visible = true;
}
}
Reading the Excel-file is no problem, my program finds it and processes it, if and only if the user changed the location by using the "Browse button" I get a message from Windows that there is already an excel file with that name and if I want to replace it, If I click away that message, my code gives an error on the line that tries to save the excel file
xlWorkbook.Save();
xlWorkbook.Close(true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlWorkbook.Save() gives me this error:
System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC Message=Verjaardagen.xlsx can not be saved,
because it's read-only.
I have no idea why I don't get an error with the default location while I do get an error if use my button to give me that same location.
Does anyone know what i'm doing wrong?
Thanks in advance
So the problem is that the file is read only when you try to write to it after going through but_Browse_Click? Are you closing the StreamReader? Try using
reader.close();
in but_Browse_Click.
Perhaps a better way would be:
using (StreamReader reader = new StreamReader(fileToOpen))
{
//all code involving the reader in here
}
This automatically closes on completion.
I have been making a text editor in c#, and recently added the functionality to silently save the file (without SaveFileDialog). The file appears to save properly, however, when trying to open the file, i get the error System.ArgumentException - File format is not valid. It opens fine if the file has not been saved silently.
The code:
The save method:
public void save(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn, string fileNameIn)
{
string fileName = "";
if (getFileFromMap(fileNameIn) != "")
{
// The file already exists in the Map so save it
fileName = getFileFromMap(fileNameIn);
StreamWriter writer = new StreamWriter(fileName);
writer.Write(rtbIn.Text);
writer.Close();
}
else
{
// The file does not exist in the Map so
// Send it to SaveAs with the rtb and the initial fileName passed in
saveAs(rtbIn, fileNameIn);
}
}
SaveAs:
public string saveAs(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn, string fileName)
{
saveDialog.FileName = fileName;
saveDialog.Title = "Save As";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
if (saveDialog.FileName.Length > 0)
{
if (saveDialog.FileName.EndsWith(".rtf"))
{
rtbIn.SaveFile(saveDialog.FileName, RichTextBoxStreamType.RichText);
}
else
{
rtbIn.SaveFile(saveDialog.FileName, RichTextBoxStreamType.PlainText);
}
addFileToMap(fileName, saveDialog.FileName);
return Path.GetFileName(saveDialog.FileName);
}
else { return ""; }
}
else { return ""; }
}
and Open:
public string open(RichTextBoxPrintCtrl.RichTextBoxPrintCtrl rtbIn)
{
if (openDialog.ShowDialog() == DialogResult.OK)
{
if (openDialog.FileName.Length > 0)
{
string fileName = Path.GetFileName(openDialog.FileName);
if (fileName.EndsWith(".rtf"))
{
rtbIn.LoadFile(openDialog.FileName, RichTextBoxStreamType.RichText);
}
else
{
rtbIn.LoadFile(openDialog.FileName, RichTextBoxStreamType.PlainText);
}
addFileToMap(openDialog.FileName, openDialog.FileName);
return fileName;
}
else { return ""; }
}
else { return ""; }
}
Other information:
The filenames are stored in a Dictionary because the editor has tabs.
RichTextBoxPrintCtrl is a custom RichTextBox that supports printing, it doesn't change anything relating to opening
The methods above are in a separate class which is why they require the richtextbox to be passed in.
If you need any other code, just let me know.
Any advice would be appreciated! Thanks in advance :)
EDIT:
Fixed, couldn't use StreamWriter.
Well, the issue seems to be that you are not saving the file in the same way.
When you perform a saveAs, you are calling rtb.SaveFile. In your silent save you are directly trying to save the rtb.Text to the file but that is probably not the correct format rtb.OpenFile is expecting.
I am no expert whatsoever in RichTextBox but spotting the difference when on method works and another similar one doesn't normally helps.
To expand a little more, Text returns only the plain text (no content formatting information). Your method save is saving as plain text any file, even if its a .rtf. Your Open method on the other hand will try to open an .rtf file as a formatted text, this can be causing the issues you are having.
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
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.
Hi all i have written a code to display a message box if invalid characters are entered while saving the file but my message box is not displaying. Actually i will have a save file dialog option to save a file if the filename starts or consists of the following
\\/:*?<>|"
I would like to display a message box as invalid or illegalcharacters in file
My code is as follows
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "(*.txt)|*.txt";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog1.FileName;
if ((FilePathHasInvalidChars(FileName)))
{
MessageBox.Show("File name should not contain \\/:*?<>|" ,"", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
//FileName = saveFileDialog1.FileName;
if (!(FilePathHasInvalidChars(FileName)))
{
TreeNode newNode = new TreeNode(FileName);
newNode.SelectedImageIndex = 1;
tvwACH.SelectedNode.Nodes.Add(newNode);
TreeNode NodeFileHeader = newNode.Nodes.Add("FileHeader");
myStream.Close();
}
}
}
}
public static bool FilePathHasInvalidChars(string path)
{
return (!string.IsNullOrEmpty(path) && path.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0);
}
Can any one help me
The SaveFileDialog class has a property called ValidateNames. It the value of that property is true(which it is by default, no need to assign it), the dialog will automatically validate that the name the the user enters does not contain any illegal characters. If the user enters an illegal file name and clicks the "Save" button, the dialog will not close, but instead show an error message:
(yes, I am currently using Windows XP)
This is because the FileDialog does this check already on himself.
If you try to use a < or a > within a filename you get an error message. If you try to use a search pattern like ? or * the ListView will be filtered for the given pattern.
Set the property ValidateNames to true in the saveFileDialog1 instance as per this MSDN. And that is set to default to be true at run-time instantiation of the 'SaveFileDialog' class.
If you're talking about having a customized error message handler to display a custom message, you need to override the SaveFileDialog by sub-classing it and intercepting the windows procedure messages for this class. Have a look at this article on CodeProject which shows how to do it.