-2

我在 a 中使用 \ 来获取文件路径

    string driveLetter = "C:\\";
    string folderName = "324Files";
    string fileName = "rpt3434.txt";
    string stringPath = driveLetter + "MainFolder\\Report" + folderName + "\\" + fileName;

我想改用@,但发现它更麻烦:

    string driveLetter = @"C:\";
    string folderName = "324Files";
    string fileName = "rpt3434.txt";
    string stringPath = driveLetter + @"MainFolder\Report" + FolderName + @"\" + fileName;

我想知道哪一种是首选的方法?

4

2 回答 2

11

Path.Combine方法就是为了解决这些困难。

string driveLetter = "C:\\";
string folderName = "324Files";
string fileName = "rpt3434.txt";
string stringPath = Path.Combine(driveLetter,"MainFolder", "Report", folderName, fileName);
Console.WriteLine(stringPath);

C:\MainFolder\Report\324Files\rpt3434.txt

或(如果您真的想将“报告”与文件夹名称连接起来

string stringPath = Path.Combine(driveLetter,"MainFolder", "Report" + folderName, fileName);

C:\MainFolder\Report324Files\rpt3434.txt

需要添加

using System.IO;

Path 类包含许多在处理用于表示文件和路径的字符串时非常有用的方法。该类还能够区分不同底层操作系统使用的语法。如果您打算将代码移植到不同的平台,那么这确实是更可取的,而硬编码的反斜杠将需要修复。

于 2013-03-27T19:48:09.807 回答
1

尝试这样的事情:

string stringPath = string.Format(@"{0}MainFolder\Report{1}\{2}", driveLetter, folderName, fileName);
于 2013-03-27T19:45:32.977 回答