请查找更新的代码。在这里,我试图打开一个存在的文件。这是代码片段。 sample.txt是获取完整的文件路径。我手动使用该路径并能够打开文本文件。但通过代码,我无法打开它。
private void button1_Click(object sender, EventArgs e)
{
//to search for a file in folder
String name_of_file = textBox1.Text;
String search_file = @"D:\Shreyas\" + name_of_file + ".txt";
System.IO.File.WriteAllText("D:\\Shreyas\\sample.txt", search_file);
//search and open the file
if(System.IO.File.Exists(search_file))
{
MessageBox.Show("File Found!!");
System.IO.File.OpenText(search_file);
}
else
{
MessageBox.Show("File Doesn't Exist!!");
}
}
答案 0 :(得分:0)
路径始终如下:
Drive:\PATH\TO\SOME\FOLDER
你的路径是:
Drive:\\PATH\\TO\\SOME\\FOLDER
您可以通过将字符串更改为:
轻松实现此功能string.Format("{0}{1}{2}{1}{3}", "D:", Path.DirectorySeparatorChar, "Folder", "file.txt");
或只是简单地说:
Path.Combine("D:","Folder", "file.txt");
答案 1 :(得分:0)
你应该尝试:
string path = @"D:\Shreyas\shreyas.txt";
System.IO.File.OpenText(path);
答案 2 :(得分:0)
编辑版本:
private void button1_Click(object sender, EventArgs e)
{
//to search for a file in folder
String name_of_file = "Test";
String search_file = @"C:\Users\User\Desktop\" + name_of_file + ".txt";
//System.IO.File.WriteAllText("D:\\Shreyas\\sample.txt", search_file);
//search and open the file
if (System.IO.File.Exists(search_file))
{
string tmp = System.IO.File.OpenText(@"C:\Users\User\Desktop\" + name_of_file + ".txt").ReadLine();
System.IO.File.WriteAllText(@"C:\Users\User\Desktop\Test_Write.txt", tmp);
}
else
{
Debug.WriteLine("Doesnt Exists");
}
}
这将读取和写入另一个文件。
尝试:@"D:\Shreyas\shreyas.txt"
字符串开头的@符号告诉C#他需要使用的路径,并为你正确格式化:)
编辑:
刚看到你的评论。阅读它使用:
string tmpString = System.IO.File.OpenText(@"C:\Users\User\Desktop\" + name_of_file + ".txt").ReadLine());
另外,请勿忘记丢弃文件阅读器。如果你不这样做,你将无法在应用程序运行时编辑你的文件。
要打开文本文件,请尝试System.Diagnostics.Process.Start(search_file);