我正在尝试检查本地计算机上的特定文件夹中是否存在文件。文件名是通过连接名和姓来创建的。我不知道如何将文件名传递到file.exists,因为文件名每次都会更改?我使用以下语句来检查文件夹。
代码:
if(File.Exists(@"C:\TestDocuments\filename.xml"))
{
MessageBox.Show("The File Already Exists");
}
答案 0 :(得分:2)
Path.Combine(String,String)连接两个字符串,带有插入的分隔符。我认为你需要的是string.format可能就像
if(File.Exists(string.Format(@"C:\TestDocuments\{0}{1}.xml",firstName,lastName))
答案 1 :(得分:0)
凯文,正如@Dai所说,你会想要使用Path.Combine
。
之后您的代码可能如下所示:
if(File.Exists(Path.Combine(directoryPath, filePath)))
{
MessageBox.Show("The File Already Exists");
}
这会将说“C:\ TestDocuments”和“filename.xml”结合起来,也可以用于其他文件名。
答案 2 :(得分:0)
你基本上可以这样做:
public static string CheckFileName(string name)
{
if(string.IsNullOrEmpty(name))
throw new ArgumentNullException();
int i = 0;
string file = Path.Combine(ConfigurationManager.AppSettings[@"FolderPath"], name);
while(File.Exist(file))
file = String.Format(file-{0}, i++);
return file;
}
这是一个非常粗略的实现,因为它不处理文件扩展名和/或值。但是如果文件存在,它应该自动递增,直到存在可用的文件名。这将减轻被覆盖的文件,但这一切都取决于您的目标。
以上 :
app.config
拉出路径,这样您就可以对其进行加密。null
。以上不
处理文件路径时,通常需要Path.Combine
以避免斜杠出现任何错误。除非存在分隔符,否则String.Format
可能遇到问题。 Microsoft Developer Network有一些很好的信息。
您应该检查System.IO
。