Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting Exception when filename has spaces in File.WriteAllBytes() c#

I have to use File.WriteAllBytes() to store the file contents.
If file.Filename is a string without spaces it works fine (like "abc","sample"). But if file.FileName comes with values like "power bi report", "March report" ,throws error.

File.WriteAllBytes($"D:\\PowerBi Console\\PowerBiConsole\\{file.FileName}.pdf",file.FileContents);

file is a FileModel instance and

public class FileModel
    {
        public byte[] FileContents { get; set; }
        public string ContentType { get; set; }
        public string FileName { get; set; }
    }

Error: The filename, directory name, or volume label syntax is incorrect

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is not the space(s), but the colon. A : is not valid in a file name. You need to replace it with e.g. dashes.

Note that if you use date.ToString() to generate (part of) a filename, it gets tricky, because different cultures use different characters as time or date separators. Many of those are not valid in a file name. You can find the list of invalid characters in a filename by querying the static method Path.GetInvalidFileNameChars().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading