Reputation: 1916
In my Windows forms project, I am trying to save a file generated into a folder called "Invoice". I am able to save to the desktop, but how can it be saved to a subfolder? I know this is very simple fix, but did some research but no luck with the solution.
PdfWriter writer = PdfWriter.GetInstance(doc,
new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\" + ord + ".pdf",
FileMode.Create));
Upvotes: 0
Views: 34416
Reputation: 9619
I don't like having everything in one line... this is what I'd do
string myFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MyFolder");
string filePath = Path.Combine(myFolder, ord + ".pdf");
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
Upvotes: 0
Reputation: 2040
You can use also Save File Dialog and replace the first argument of FileStream with path that Save File Dialog returns.
Upvotes: 0
Reputation: 1602
If the folder does not exist then you need to create the folder and then write
Directory.CreateDirectory Method (String)
Creates all directories and subdirectories as specified by path.
Example:
string fileName = @"C:\Users\SomeUser\My Documents\Foo\Bar\Baz\text1.txt";
Directory.CreateDirectory(Path.GetDirectoryName(fileName));
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
// ...
}
once done you can write into the folder like this
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Invoice\\" + ord + ".pdf", FileMode.Create));
Upvotes: 0
Reputation: 727047
You can add the name of the folder in the same way that you add the name of the file:
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Invoice\\" + ord + ".pdf", FileMode.Create));
// ^^^^^^^^^^^^
You can also use string.Format
to compose the path, like this:
var pathToPdf = string.Format(
"{0}\\{1}\\{2}.pdf"
, Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
, "Invoice"
, ord
);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pathToPdf, FileMode.Create));
Upvotes: 4