C#文件操作

1.创建文件

 public void CreateFile()
        {
            string path = "D:/PS/test/x/properties.txt";
            if (!File.Exists(path))//判断文件是否存在
            {
                try
                {//创建文件
                    File.Create(path).Close();
                }
                catch (Exception e){}
            }
            else
            {
                label_last.Text = "文件已存在";
            }
            /*
             String x = "proper.txt";
             String directory = "D:\\PS\\test";
             if (!Directory.Exists(directory))
             {
                 Directory.CreateDirectory(directory);
             }
            else
            {
                string path = directory + "\\" + x;
                if(!File.Exists(directory){
                    File.Create(path).Close();
                }
                
            }*/
        }

2. 写文件

 public void wirteFile(string path, string data)
        {
            FileStream fs = new FileStream(path,FileMode.Create, FileAccess.ReadWrite);
            StreamWriter streamWriter = new StreamWriter(fs);
            streamWriter.WriteLine(data);
            streamWriter.Flush();
            streamWriter.Close();
        }

3.读文件并修改值

        public void ReadFile(string path)
        {
            List<string> list = new List<string>();
            using (StreamReader sr = new StreamReader(path))
            {
                string s = sr.ReadLine();
                while (s != null)
                {
                    list.Add(s);
                    s = sr.ReadLine();
                }
                sr.Close();
            }
            // 创建一个StringBuilder用来保存数据,
            //    若满足要修改的条件,则将修改后的数据保存在StringBuilder中
            //    若不满足则直接追加到StringBuilder后面
            // 修改完数据后,将该StringBuilder中的数据写入文件中
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < list.Count; i++)
            {
                string sou = "dsffs4";
                if (list[i].Contains(sou))
                {
                    string x = list[i];
                    int se = sou.Length;
                    string str1 = x.Substring(se);
                    int num = int.Parse(str1) + 1;
                    stringBuilder = stringBuilder.AppendLine(sou + num);
                }
                else
                {
                    stringBuilder.AppendLine(list[i]);
                }
            }
            wirteFile(path, stringBuilder.ToString());
        }

4. 清空文件

 public void ClearFile(string path)
{
       FileStream fs = new FileStream(path, FileMode.Truncate, FileAccess.ReadWrite);
       fs.Close();
}

5. 删除文件

File.Delete(path);

posted @ 2022-09-25 20:57  浑浑噩噩一只小迷七  阅读(32)  评论(0)    收藏  举报