在 C# 中构建文件路径的最佳实践
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10704579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best practice for building file paths in C#
提问by zalpha314
I'm working on a C# project where I must build paths to various files and folders. These are all under one root folder which I have specified in my Web.config file.
我正在处理一个 C# 项目,我必须在其中构建各种文件和文件夹的路径。这些都在我在 Web.config 文件中指定的一个根文件夹下。
For example:
例如:
- "start with: "D:\builds\" from my Web.config
- Pass to GetRelativePath() to get "D:\builds\5.2\5.2.9751"
- Then pass to GetAutoSuitePath() to get "D:\builds\5.2\5.2.9751\AutoSuite\"
- Then pass to ParseBrLog which will read "D:\builds\5.2\5.2.9751\AutoSuite\AASanity.csv"
- “从我的 Web.config 中的“D:\builds\”开始
- 传递给 GetRelativePath() 得到“D:\builds\5.2\5.2.9751”
- 然后传递给 GetAutoSuitePath() 得到“D:\builds\5.2\5.2.9751\AutoSuite\”
- 然后传递给 ParseBrLog,它将读取“D:\builds\5.2\5.2.9751\AutoSuite\AASanity.csv”
My paths are correct, but I just want to know what the best practice is for incomplete paths. Should I add a "\" to the end of every folder ("D:\Builds\5.2\" + "test.txt"), or add one to the start of every folder/file I add to the path ("D:\Builds" + "\5.2" + "\test.txt")? Currently, I'm, doing it both ways, and want to choose one uniform way of doing it.
我的路径是正确的,但我只想知道不完整路径的最佳实践是什么。我应该在每个文件夹的末尾添加一个“\”(“D:\Builds\5.2\”+“test.txt”),还是在我添加到路径的每个文件夹/文件的开头添加一个(“D :\Builds" + "\5.2" + "\test.txt")?目前,我正在以两种方式进行,并且想要选择一种统一的方式来做。
采纳答案by Oded
Use the Pathclass to build up your paths. It will do the right thing.
使用Path该类来构建您的路径。它会做正确的事情。
Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
对包含文件或目录路径信息的 String 实例执行操作。这些操作以跨平台的方式执行。
var full = Path.Combine(baseDir, dirFragment);
回答by Matteo Migliore
Use Path.Combineto concatenate path tokens.
使用Path.Combine连接路径标记。
If the path is a file to set/change the extension use Path.ChangeExtension.
如果路径是设置/更改扩展名的文件,请使用Path.ChangeExtension。

