Reputation: 20648
Um trying to create a pdf file with the file name as follows
Hello 1115 Apple Mango 27.08.2015 00:00:00.pdf
using
var tempFileName = Fruit.Name + " " + numberName + " " + DateTime.Now.Date.ToString() + ".pdf";
var pdfFile = Path.Combine(Path.GetTempPath(), tempFileName);
System.IO.File.WriteAllBytes(pdfFile, Pdfcontent.GetBuffer());
Please note that my file name contain spaces, if I create a file name without spaces it will generate a file without any issues
Since it's containing spaces it throws an exception {"The given path's format is not supported."}
The Generated filepath looks something like this C:\Users\Sansa\AppData\Local\Temp\Hello 1115 Apple Mango 27.08.2015 00:00:00.pdf
How to fix this issue
Upvotes: 0
Views: 1373
Reputation: 2296
The problem isn't in spaces. There are a few symbols, that deniend in naming: <
, >
, :
, "
, /
, \
, |
, ?
, *
. Also you can check the rules for naming files and folders on MSDN.
You can fix this issue by replacing this symbols to allowed. In your case you can use simple replace
:
tempFileName = tempFileName.Replace(':', '_'); // prevent using : symbol
But much better is to get all unallowed symbols and use Regex to prevent using them:
var pattern = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
var r = new Regex(string.Format("[{0}]", Regex.Escape(pattern)));
tempFileName = r.Replace(tempFileName, "_");
If you choose second variant, don't forget to add namespaces in your file:
using System.IO;
using System.Text.RegularExpressions;
Upvotes: 2
Reputation: 5157
:
are not allowed in the file names. You could remove them.
Also you could replace spaces with the underscores _
if you want.
Upvotes: 3