注册 登录
编程论坛 C# 论坛

C#文件读写求助一直遇到 流不可写问题~~~~

hdusec 发布于 2015-05-04 21:10, 780 次点击
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using

namespace arraylist
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream aFile = new FileStream(@"D:\test1.txt", FileMode.OpenOrCreate,FileAccess.ReadWrite);     
            StreamReader sr = new StreamReader(aFile);
            int charCode = sr.Read();
            char[] ch=new  char[100];
            int i = 0;
            while(charCode!=-1)
            {
                 ch[i]=Convert.ToChar(charCode);
                charCode=sr.Read();
                i++;
            }         
            string str1 = new string(ch);
            sr.Close();
            StreamWriter sw = new StreamWriter(aFile);
            string str2 = "ok";
            char[] chs = { 'p', 'c' };
            for ( i = 0; i < aFile.Length + 2; i++)
            {
                if (str1.Substring(i, 2) == str2)
                {
                    sw.Write(chs, i, 2);
                }
            }
            Console.WriteLine(str1);
            Console.ReadKey();
        }
    }
}
代码一直卡死在 StreamWriter sw = new StreamWriter(aFile);这一步,可是我的aFile明明已经设置为可读写了啊~~为什么还是说不可写呢,
这个代码是要在test.txt内容上找到有OK字符的地方,然后加上字母pc。
不知道为什么会报这个错。。求大神解答。
1 回复
#2
八画小子2015-05-05 01:59
sr.Close();
这一句已经把文件流给关闭了,当然不可写了。
1