当文件名在 File.WriteAllBytes() 中包含空格时出现异常 c# [duplicate]

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

提问人:Muhammed Irshad 提问时间:4/5/2023 更新时间:4/6/2023 访问量:196

问:

我必须使用 File.WriteAllBytes() 来存储文件内容。 如果是一个没有空格的字符串,它可以正常工作(如“abc”,“sample”)。但是,如果带有“power bi report”、“March report”等值,则会引发错误。file.Filenamefile.FileName

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

file是一个实例,并且FileModel

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

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

C# net-5 系统.io.file

评论

3赞 jmcilhinney 4/5/2023
这不是空间。是冒号。也许您应该检查文件名中允许哪些字符。这不是编程问题,而只是一个简单的计算机使用问题。

答:

1赞 PMF 4/5/2023 #1

问题不在于空格,而在于冒号。A 在文件名中无效。您需要将其替换为破折号。:

请注意,如果您用于生成(部分)文件名,它会变得棘手,因为不同的区域性使用不同的字符作为时间或日期分隔符。其中许多在文件名中无效。您可以通过查询 static 方法 来查找文件名中的无效字符列表。date.ToString()Path.GetInvalidFileNameChars()