2015-10-06 84 views
1
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly 
         .GetExecutingAssembly().Location + 
          @"\keyfile\EmailbodyorFile.txt"); 

我用这个来获取路径,但我的问题是“EmailbodyorFile.txt”必须在运行时和上面的代码不会创建该文件自动创建。那么该怎么办?寻找路径和C#Windows会自动创建一个文件

早些时候,我用这个代码,

string path = Path.GetFullPath(System.AppDomain.CurrentDomain.BaseDirectory + 
@"\keyfile\EmailbodyorFile.txt"); 

并正常运行,但创建项目的设置后,它显示错误“未找到错误文件”。

请大家帮忙。

+0

如何,如果你没有为它写代码会奇迹般地创建文件?你需要使用File类。使用File.Exists方法检查文件是否存在于同一位置,如果不存在,则创建它。 – niksofteng

+1

你应该检查目录是否存在,如果它不是 - 通过Directory.Create(...)创建,当检查文件存在时,如果它不是 - 通过File.Create创建(...) –

+0

这是一个Windows窗体或一个WPF应用程序? – Sayka

回答

0
//Check for existence of file 
string filePath=System.IO.Directory.GetCurrentDirectory() + @"\keyfile\EmailbodyorFile.txt" 
if(!File.Exists(filePath) 
{ 
    //If not existing then create it  
    File.Create(filePath); 
} 
using (StreamWriter FileWriter= File.AppendText(filePath))) 
{ 
    FileWriter.WriteLine("Your Content string");    
} 
+0

当我尝试创建给出错误时,无法找到路径'F:\ Encryptingmail \ OurEnctyption \ bin \ Debug \ OurEnctyption.exe \ keyfile \ EmailbodyorFile.txt'的一部分。 – sayana

+0

这意味着你给出的路径不是创建文件的有效路径,我已经更新了答案,请检查它\ –

+0

Btw如果文件不存在,File.AppendText会创建该文件,因此检查其文件这里没有必要存在。 – vesan

0

尝试

string path = System.IO.Path.Combine(
        System.IO.Path.GetDirectoryName(Application.ExecutablePath), 
        @"\keyfile\EmailbodyorFile.txt"); 
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)); 
0
string path = System.AppDomain.CurrentDomain.BaseDirectory + "\\KeyFile"; 
string file = "EmailbodyorFile.txt"; 

if (!System.IO.Directory.Exists(path)) 
    System.IO.Directory.CreateDirectory(path); 

打开,如果存在,或者创建如果不

System.IO.FileStream fs = new System.IO.FileStream(path + "\\" + file, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); 

你能读到这样

System.IO.StreamReader sr = new System.IO.StreamReader(fs); 
string fileContents = sr.ReadToEnd(); 
sr.Close(); 

或者可以编写

System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); 
string writeToFile = "I want to add this to my newly created file"; 
sw.Write(writeToFile); 
+0

谢谢大家 – sayana

+0

@sayana,如果你觉得任何帖子感激,你可以点击upvote按钮,或者将它标记为答案。 – Sayka