如何在两个字符串之间添加'/'?

Ana*_*oly 0 c#

我有以下代码:

if (!string.IsNullOrEmpty(_location.FolderName))
{
    name = _location.FolderName + '/' + name;
}
Run Code Online (Sandbox Code Playgroud)

/在两个字符串之间添加是否正确?或者我应该使用以下代码:

if (!string.IsNullOrEmpty(_location.FolderName))
{
    name = _location.FolderName + "/" + name;
}
Run Code Online (Sandbox Code Playgroud)

Mik*_*son 13

对于连接文件路径,您应该使用该System.IO.Path.Combine方法.

using System.IO;
...

if (!string.IsNullOrEmpty(_location.FolderName))
{
    name = Path.Combine(_location.FolderName, name);
}
Run Code Online (Sandbox Code Playgroud)

有一点需要注意,正如Anton在下面的评论中提到的那样,你必须确保路径中的字符有效,你可以在文档中找到更多信息.

  • @AntonGogolev当你试图获得一个有效的路径作为输出时,这是一个非常好的行为:) (4认同)