自动查找路径并在c#窗口中创建文件

时间:2015-10-06 05:01:58

标签: c# winforms

string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly
                      .GetExecutingAssembly().Location + 
                           @"\keyfile\EmailbodyorFile.txt");

我用它来获取路径,但我的问题是'EmailbodyorFile.txt'必须在运行时自动创建,上面的代码不会创建文件。那该怎么办?

之前我使用过这段代码,

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

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

请帮忙。

3 个答案:

答案 0 :(得分: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");              
}

答案 1 :(得分:0)

尝试

string path = System.IO.Path.Combine(
                    System.IO.Path.GetDirectoryName(Application.ExecutablePath),
                    @"\keyfile\EmailbodyorFile.txt");
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));

答案 2 :(得分:0)

 for(int i=0;i<apples.rows;i++)
            {
                for(int j=0;j<apples.cols;j++)
                    {
                     // read whole pixel value, which is a Vec3b for most color images. If you only read uchars you would have to multiply column index by 3 and add the channel number (0..2)
                     cv::Vec3b & pixel = applescopy[0].at<Vec3b>(i,j)
                     // decompose the pixel to three channels
                     uchar & B = pixel[0];
                     uchar & G = pixel[1];
                     uchar & R = pixel[2];
                     // test for any condition, e.g. if one of RGB is 0
                        if( anyCondition )
                          {
     //set whole Vec3b to some value
                            apples.at<Vec3b>(i,j) = black;
                          }
                    }
            }

如果存在则打开,否则创建

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();