-2

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

  • 3
    It's not the spaces. It's the colons. Maybe you should check what characters are allowed in a file name. This is not a programming issue but just a simple computer use issue. – jmcilhinney Apr 05 '23 at 07:17

1 Answers1

1

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().

PMF
  • 14,535
  • 3
  • 23
  • 49