Set the PDF file name in C# - c#

I am generating a PDF file with C#. The title of the file is assigned automatic. I want to set the file name when I open the folderbrowserdialog . How can i do that?
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string caminho = folderBrowserDialog1.SelectedPath;
var pasta2 = caminho.Replace(#"\", #"\\");
Document doc = new Document(PageSize.A4.Rotate(), 10, 10, 42, 35);
PdfWriter.GetInstance(doc, new FileStream(pasta2 + "\\Relatorio.pdf", FileMode.Append, FileAccess.Write));

Try Something Like, You have to use SaveFileDialog , For more information visit MSDN
SaveFileDialog dialog1 = new SaveFileDialog();
dialog1.Title = "Save file as...";
dialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
dialog1.RestoreDirectory = true;
if (dialog1.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(dialog1.FileName);
}
you use dialog1.FileName when creating your FileStream:
PdfWriter writertest = PdfWriter.GetInstance(doc, new FileStream(dialog1.FileName, FileMode.Create));
Hope it works for you.

You can't set the Filename in FolderBrowserDialog, you need to use SaveFileDialog. Try this sample code
saveFileDialog1.FileName = "Akshay.pdf";
saveFileDialog1.FileOk +=new CancelEventHandler(saveFileDialog1_FileOk);
saveFileDialog1.ShowDialog();
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
// MessageBox.Show("Done");
// do the PDF Method here
}

Related

Save stream of savefiledialog in c#

In my wpf app I have an "Export" button that suppose to save some json file to chosen path.
I mean my question is how to write the file, let's say he has the path D:\somefile.json to the chosen location that the user chose from save dualog?
Here my code:
void Export_button_Click(object sender, RoutedEventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Json files (*.json)|*.json";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
This should be something like:
Copy(StreamOf(D:\somefile.json),ChosenPath)
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "Json files (*.json)|*.json";
sf.FilterIndex = 2;
sf.RestoreDirectory = true;
if (sf.ShowDialog() == DialogResult.OK)
{
System.IO.File.Copy(#"D:\somefile.json", sf.FileName, true);
}
you can use File.copy
public static void Copy(
string sourceFileName,
string destFileName)
for more info you can visit https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx

Overwriting a text file from RichTextBox

Now if you write the text and click on the save button, OpenFileDialog will appear. If you finish something in the same document and click on the save button again, you need to select the save location again. How to make that when saving the same file you do not need to create a new file each time, and just overwrite the current one? Sorry for my English.
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
}
else
{
}
}
It sure is, you just need to remember the last file path you saved and not display the dialog again the next time around; something like this should help:
void Main()
{
Save();
}
private string _filePath = "";
void Save()
{
var overwrite = false;
if (!string.IsNullOrEmpty(_filePath))
{
var res =
MessageBox.Show("Would you like to overwrite your last saved file?", "Overwrite?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly, false);
if (res == DialogResult.Cancel) return;
if (res == DialogResult.No) overwrite = false;
if (res == DialogResult.Yes) overwrite = true;
}
if (!overwrite)
{
var sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File|*.rtf";
var res = sfd.ShowDialog();
if (res != DialogResult.OK) return;
_filePath = sfd.FileName;
}
// do the richTextBox.SaveFile(_filePath) here.
}
In this example it:
CHECK IF FILE PATH ALREADY SET
IF NOT THEN
ASK USER IF THEY WANT TO OVERWRITE THE LAST FILE
IF CANCEL THEN DON'T SAVE
IF YES THEN SET OVERWRITE TO TRUE
IF NO THEN SET OVERWRITE TO FALSE
END IF
CHECK IF OVERWRITING
IF OVERWRITING THEN
SHOW SAVE FILE DIALOG
IF USER DIDN'T CLICK OK THEN DON'T SAVE
IF USER CLICKED OK, SET THE NEW FILE PATH TO USE
END IF
SAVE THE FILE USING THE NOW-REMEMBERED FILE PATH
Perhaps:
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = saveFileDialog1.FileName;
}
}
Example from: http://www.c-sharpcorner.com/uploadfile/mahesh/savefiledialog-in-C-Sharp/
Might help some?
private string filePath = string.Empty;
private void SaveButton_Click(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
byte[] buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
MemoryStream ms = new MemoryStream(buffer);
//write to file
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
filePath = sfd.FileName;
}
}
}
you can use sfd.OverwritePrompt = false; property to avoid prompt messagebox if file already exists, is this what you are looking for ?

Save file to specific folder in C# using SaveFileDialog

I need to save a file using SaveFileDialog to a specific folder.
For example, say we want to save in "c:\MyNewFolder". If the folder doesn't exist, create it and save there, or only save there if the folder does exist.
String fileName="";
String date = DateTime.Now.Day+"-"+DateTime.Now.Month+"-"+DateTime.Now.Year;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (Stream s = File.Open(saveFileDialog1.FileName,FileMode.CreateNew))
using (StreamWriter sw = new StreamWriter(s))
{
sw.WriteLine(tbName.Text);
sw.WriteLine(tbSummary.Text);
}
}
You can look for
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "c:\\MyNewFolder";
save.RestoreDirectory = true;
string strPath="c:\MyNewFolder";
if (!Directory.Exists(strPath))
{
Directory.CreateDirectory(strPath);
}
else
{
//Continue your logic and append your file name
}

Attempted to read or write protected memory. This is often an indication that other memory is corrupt

I'm working on a windows form project and it creates a PDF file. I want to save file where user want it to. I use a SaveFileDialog for this. When I click "Save as a PDF" button on my form I get this error code.
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
If I don't use the SaveFileDialog (If I give a static name for the file), don't get the error.
Here is button click code:
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "(*.pdf)|*.pdf|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document(PageSize.A4, 20, 20, 10, 10);
PdfWriter.GetInstance(pdfDosya, new FileStream(saveFileDialog1.FileName, FileMode.Create));//TODO dosya ismi
pdfDosya.Open();
}
}
How can I solve the problem.
This could be the problem:
You can't use Convert.ToString(Environment.SpecialFolder.MyDocuments) to get the folder path as a string, it's only a enum. You need to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) to get the path as a string for the enum value.
Try this code
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "(*.pdf)|*.pdf|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
MemoryStream ms = new MemoryStream();
iTextSharp.text.Document document = new Document(PageSize.A4, 10.0F, 10.0F,100.0F,0.0F);
document.AddTitle("FileName.pdf");
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
}

how do you save from a savefile dialog in C#?

here is the code I am currently using to open a file using the openfiledialog `
private void openToolStripMenuItem_Click_1(object sender, System.EventArgs e)
{
//opens the openfiledialog and gives the title.
openFileDialog1.Title = "openfile";
//only opens files from the computer that are text or richtext.
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
//gets input from the openfiledialog.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//loads the file and puts the content in the richtextbox.
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = (sr.ReadToEnd());
sr.Close();` here is the code I am using to save through a savefiledialog `
Stream mystream;
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((mystream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(mystream);
wText.Write("");
mystream.Close();
`
It allows me to open text files but I can't save changes nor create my own text file. no errors are shown during run time. Thanks again for the extra help.
The SaveFileDialog doesn't do the actual saving for you; it simply allows the user to specify a file path. You use the file path and then do the heavy lifting with an implementation of the StreamWriter class, something like:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using( Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew) )
using( StreamWriter sw = new TextWriter( s ) )
{
sw.Write( someTextBox.Text );
}
}

Categories