在C#中建立文件路径的最佳实践 [英] Best practice for building file paths in C#

查看:189
本文介绍了在C#中建立文件路径的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个C#项目中,我必须建立路径的各种文件和文件夹。这些都是根据我在Web.config文件中已经指定了一个根文件夹



例如:




  1. 传递给GetRelativePath()得到\builds\ D::>
  2. 开始:D \builds \5.2\5.2.9751

  3. 然后传递给GetAutoSuitePath()得到D:\builds\5.2\5.2.9751\AutoSuite\

  4. 然后传递给ParseBrLog将改为D:\builds\5.2\5.2.9751\AutoSuite\AASanity.csv



我的路径是正确的,但我只是想知道最好的做法是不完整的路径,我要补充一个\每一个文件夹(D的结尾: \Builds\5.2\+的test.txt),或添加一个至每个文件夹/文件I添加到路径(开始的D:\Builds+\5.2+\\ \\test.txt)?目前,我,做左右逢源,并要选择做一个统一的方式。


解决方案

使用 路径 类来建立你的路径。它会做正确的事。




执行对包含文件或目录路径信息的String实例操作。这些操作在一个跨平台的方式进行。




  VAR全= Path.Combine( BASEDIR,dirFragment); 


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.

For example:

  1. "start with: "D:\builds\" from my Web.config
  2. Pass to GetRelativePath() to get "D:\builds\5.2\5.2.9751"
  3. Then pass to GetAutoSuitePath() to get "D:\builds\5.2\5.2.9751\AutoSuite\"
  4. Then pass to ParseBrLog which will read "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.

解决方案

Use the Path class to build up your paths. It will do the right thing.

Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.

var full = Path.Combine(baseDir, dirFragment);

这篇关于在C#中建立文件路径的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆