c#小软件(SaveClassic)开发手记(3)基础类(文件操作类FileOption)

该操作类的功能是实现对文件的删除,修改查询功能,该类基本完成了对文件的操作,同样是用最简单的代码实现了文件操作功能。具体代码如下所示。

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

namespace Common

{

    public class FileOption

    {

        public FileOption()

        {

        }

 

        /// <summary>

        ///按时间获取文件名称

        /// </summary>

        /// <returns></returns>

        public static string GetFileName()

        {

            string filename = DateTime.Now.ToString("yyyMMddHHmmss");

            return filename;

        }

 

        /// <summary>

        /// 保存文件

        /// </summary>

        /// <returns></returns>

        public static bool SaveFile(string Path, string Strings,string PostfixStr)

        {

            try

            {

                Path += @"\"+GetFileName()+"."+PostfixStr;

                //if (!System.IO.File.Exists(Path))

                //{

                //    FileStream f = File.Create(Path);

                //    f.Close();

                //}

                StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));

                f2.Write(Strings);

                f2.Close();

                f2.Dispose();

                return true;

            }

            catch (Exception ex)

            {

                return false;

            }

        }

//保存字符到文件

        public static String SaveFileR(string Path, string Strings, string PostfixStr)

        {

            try

            {

                string filename = GetFileName();

                Path += @"\" + filename + "." + PostfixStr;

                StreamWriter f2 = new StreamWriter(Path, false, System.Text.Encoding.GetEncoding("gb2312"));

                f2.Write(Strings);

                f2.Close();

                f2.Dispose();

                return filename;

            }

            catch (Exception ex)

            {

                return "";

            }

        }

//读取文件内容到字符串

        public static string OpenFile(string Path)

        {

           return File.ReadAllText(Path);

        }

 

//获取某文件夹所有文件

        public static string[] GetFiles(string Path)

        {

           return Directory.GetFiles(Path);

        }

    }

}

好了,所有的文件操作代码已经编写完毕,该类的使用方法也很简单,在日后的开发中使用的时候就能知道是如何简单实用的。

原文地址:https://www.cnblogs.com/studyplay/p/2279372.html