文件创建问题 [英] file create problem

查看:87
本文介绍了文件创建问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时会显示以下错误:

when run this code this error is shown:

System.IO.IOException.



进程无法访问文件'C

我的代码如下:


The process cannot access the file 'C
my code is below:

func pageload(){
 string path = @"D:\\Yourfile.txt";
string givenText = "";
        if (File.Exists(path))
        {
            StreamReader sr = new StreamReader(path);
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    givenText = givenText + s + Environment.NewLine;
                }

                sr.Close();
                sr.Dispose();
        }
        FileStream fs1 = new FileStream(path, FileMode.OpenOrCreate, ileAccess.Write);
        StreamWriter writer = new StreamWriter(fs1);

        writer.WriteLine(givenText +"la la la ala");
        writer.Close();
        writer.Dispose();
}

推荐答案

问题是你将两种字符串形式合二为一:

The problem is that you are using both string forms in one:
string path = @"D:\ \Yourfile.txt";

用其中一个替换它可以解决你的问题:

Replacing that with one of these should cure your problem:

string path = @"D:\Yourfile.txt";



Or

string path = "D:\\Yourfile.txt";



但是......这是一个非常糟糕的方法!

首先要更有效地做到这一点:


But...that's a very bad way to do it!
Start by doing that more efficiently:

if (File.Exists(path)) givenText = File.ReadAllText(path);



然后在一个中使用StreamWriter 使用



或者,用以下方法替换整个方法:


and then use the StreamWriter in a using block

Alternatively, replace the whole method with this:

private void pageload()
   {
   File.AppendAllText(@"D:\YourFile.txt", "la la la ala" + Environment.NewLine);
   }


这篇关于文件创建问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆