C# 如何验证字符串提供的文件路径是否为有效的目录格式?
我这里有一个相当直截了当的问题,但每次我必须处理文件路径和名称的验证时,我似乎都会重新考虑这个问题。所以我想知道在C# 如何验证字符串提供的文件路径是否为有效的目录格式?,c#,.net,file-io,C#,.net,File Io,我这里有一个相当直截了当的问题,但每次我必须处理文件路径和名称的验证时,我似乎都会重新考虑这个问题。所以我想知道在System.IO或框架中的其他库中是否有一种方法可以让我的生活更轻松 让我们以一个精心设计的方法为例,该方法获取文件路径和文件名,并从这些输入中格式化并返回唯一的完整文件位置 public string MakeFileNameUnique(string filePath, string fileName) { return filePath + Guid.NewGuid(
System.IO
或框架中的其他库中是否有一种方法可以让我的生活更轻松
让我们以一个精心设计的方法为例,该方法获取文件路径和文件名,并从这些输入中格式化并返回唯一的完整文件位置
public string MakeFileNameUnique(string filePath, string fileName)
{
return filePath + Guid.NewGuid() + fileName;
}
我知道我必须执行以下操作以获得正确格式的路径,以便可以附加guid和文件名:
- 若filePath为null或空,则引发异常
- 如果文件路径不存在,则引发异常
- 如果没有有效的后缀“/”,则添加一个
- 如果它包含一个后缀“\”,则删除并替换为“/”
makefilenameinque
),你考虑过使用这个方法吗?还是方法?您正在寻找方法:
但是看看你的方法的名称(
makefilenameinque
),你考虑过使用这个方法吗?还是方法?按照您的要求,这样就可以了
public string MakeFileNameUnique(string filePath, string fileName)
{
// This checks for nulls, empty or not-existing folders
if(!Directory.Exists(filePath))
throw new DirectoryNotFoundException();
// This joins together the filePath (with or without backslash)
// with the Guid and the file name passed (in the same folder)
// and replace the every backslash with forward slashes
return Path.Combine(filePath, Guid.NewGuid() + "_" + fileName).Replace("\\", "/");
}
打电话给
string result = MakeFileNameUnique(@"d:\temp", "myFile.txt");
Console.WriteLine(result);
将导致
d:/temp/9cdb8819-bdbc-4bf7-8116-aa901f45c563_myFile.txt
但是,我想知道按照您的要求将反斜杠替换为正斜杠的原因
public string MakeFileNameUnique(string filePath, string fileName)
{
// This checks for nulls, empty or not-existing folders
if(!Directory.Exists(filePath))
throw new DirectoryNotFoundException();
// This joins together the filePath (with or without backslash)
// with the Guid and the file name passed (in the same folder)
// and replace the every backslash with forward slashes
return Path.Combine(filePath, Guid.NewGuid() + "_" + fileName).Replace("\\", "/");
}
打电话给
string result = MakeFileNameUnique(@"d:\temp", "myFile.txt");
Console.WriteLine(result);
将导致
d:/temp/9cdb8819-bdbc-4bf7-8116-aa901f45c563_myFile.txt
但是,我想知道将反斜杠替换为正斜杠的原因想删除同一路径中反斜杠和正斜杠的混合。想删除同一路径中反斜杠和正斜杠的混合。path.Combine只接受两个参数?是,我考虑同时使用Path.GenerateRandomFileName或Path.GetTempFileName方法,但这两种方法都不足以满足我的需要。@fin:
Path.Combine
可以接受任意数量的参数,因为它的一个重载是params
重载。例如,Path.Combine()。这些重载已添加到.Net 4.0中。对于早期版本,使用对Path.Combine
.Path.Combine的嵌套调用只需要两个参数?是的,我考虑同时使用Path.GenerateRandomFileName或Path.GetTempFileName方法,但这两种方法都不足以满足我的需要。@fin:Path.Combine
可以接受任意数量的参数,因为它的重载之一是params
重载。例如,Path.Combine()。这些重载已添加到.Net 4.0中。对于早期版本,请使用对Path.Combine
的嵌套调用。