简体   繁体   中英

C# Exception when creating a file when file name has spaces throws an error {“The given path's format is not supported.”}

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

: are not allowed in the file names. You could remove them.

Also you could replace spaces with the underscores _ if you want.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM