[翻译][.NET Tip of The Day] System.IO.Path 几个容易忘记使用的方法介绍(标题为译者拟, 两篇合一)
译者手记: 因为这两篇都是关于 System.IO.Path 下面的方法, 所以放在一篇方便查阅.
========================
译自: http://dotnettipoftheday.org/tips/SystemIOPathCombine.aspx
考虑使用 System.IO.Path.Combine() 而不是字符串连接
(Consider using System.IO.Path.Combine() instead of string concatenation)
让我们来看看下面这段创建一个文件路径的代码:
public string GetFullPath(string fileName)
{
string folder = ConfigurationManager.AppSettings["MyFolder"];
return folder + fileName;
}
这段代码很可能导致错误. 比如, 当你设置文件夹配置, 你必须记住确保它以斜线结尾. 为了避免这种问题, 使用 Path.Combine() 方法来确保文件夹(的路径)有结束斜线:
public string GetFullPath(string filename)
{
string folder = ConfigurationManager.AppSettings["MyFolder"];
return Path.Combine(folder, filename);
}
======================================================================
下面这段译自:http://dotnettipoftheday.org/tips/PathGetRandomFileName.aspx
当处理临时文件的时候,使用 Path.GetRandomFileName() 或者 Path.GetTempFileName()
(Use Path.GetRandomFileName() or Path.GetTempFileName() when working with temp files)
不要重新实现为临时文件产生唯一的名字的函数. 使用下面其中一个已经存在的方法:
- System.IO.Path.GetTempFileName() - 如果你想在用户临时目录创建临时文件, 使用此方法.
- System.IO.Path.GetRandomFileName() - 如果你仅仅是想产生唯一的名字, 使用这个方法.