当前位置:编程学习 > C#/ASP.NET >>

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 "";

 

            }

 

        }

 

//读取文件内容到字符串 www.zzzyk.com

 

        public static string OpenFile(string Path)

 

        {

 

           return File.ReadAllText(Path);

 

        }

 

 

 

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

 

        public static string[] GetFiles(string Path)

 

        {

 

           return Directory.GetFiles(Path);

 

        }

 

    }

 

}

 

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

作者 zhaoyang

补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,