C# 将文件保存在特定文件夹中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15321925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save file in specific folder
提问by Amrit Sharma
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.
在我的 Windows 窗体项目中,我试图将生成的文件保存到名为“发票”的文件夹中。我可以保存到桌面,但如何保存到子文件夹?我知道这是非常简单的修复,但做了一些研究,但没有解决问题。
PdfWriter writer = PdfWriter.GetInstance(doc,
new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\" + ord + ".pdf",
FileMode.Create));
采纳答案by dasblinkenlight
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:
您还可以使用string.Format
来组成路径,如下所示:
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));
回答by Hyman Pettinger
Replace the "\\" with "\Invoice\" + ord + ".pdf"
将“\\”替换为“\Invoice\”+ ord +“.pdf”
回答by Travis G
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));
回答by CAPS LOCK
You can use also Save File Dialogand replace the first argument of FileStream with path that Save File Dialog returns.
您还可以使用“保存文件对话框”并将 FileStream 的第一个参数替换为“保存文件对话框”返回的路径。
回答by sebagomez
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));