C#操作文件

2017-12-12  本文已影响0人  玛玛哈哈m

读文件

    public static string Read()
    {
        if (File.Exists(filePath))
        {
            var sr = File.OpenText(filePath);
            string str = sr.ReadToEnd();
            sr.Close();

            return str;
        }

        return null;
    }
    public static void ReadLine()
    {
        if (File.Exists(filePath))
        {
            var sr = File.OpenText(filePath);
            string str;
            int num = 0;

            while ((str = sr.ReadLine()) != null)
            {
                num++;                
            }

            sr.Close();           
        }
    }

检查文件大小

    public static int CheckSize()
    {
        if (File.Exists(filePath))
        {
            //FileVersionInfo info = FileVersionInfo.GetVersionInfo(path);
            //Console.WriteLine("文件名称=" + info.FileName);
            //Console.WriteLine("产品名称=" + info.ProductName);
            //Console.WriteLine("公司名称=" + info.CompanyName);
            //Console.WriteLine("文件版本=" + info.FileVersion);
            //Console.WriteLine("产品版本=" + info.ProductVersion);
            //// 通常版本号显示为「主版本号.次版本号.生成号.专用部件号」
            //Console.WriteLine("系统显示文件版本:" + info.ProductMajorPart + '.' + info.ProductMinorPart + '.' + info.ProductBuildPart + '.' + info.ProductPrivatePart);
            //Console.WriteLine("文件说明=" + info.FileDescription);
            //Console.WriteLine("文件语言=" + info.Language);
            //Console.WriteLine("原始文件名称=" + info.OriginalFilename);
            //Console.WriteLine("文件版权=" + info.LegalCopyright);

            //Console.WriteLine("文件大小=" + System.Math.Ceiling(fileInfo.Length / 1024.0) + " KB");

            FileInfo file = new FileInfo(filePath);
            int kb = Mathf.CeilToInt(file.Length / 1024f);

            return kb;
        }

        return -1;
    }

写文件

StreamWriter方式

    static void WriteByStream(string str)
    {
        var sw = File.AppendText(filePath);
        sw.Write(str+ NewLineStr);
        sw.Flush();
        sw.Close();
    }

FileStream方式

    static void WriteBytes(string str)
    {
        var fs = File.OpenWrite(filePath);
        //设定书写的開始位置为文件的末尾  
        fs.Position = fs.Length;
        //将待写入内容追加到文件末尾  
        byte[] bytes = GetBytes(str + NewLineStr);
        fs.Write(bytes, 0, bytes.Length);
        fs.Flush();
        fs.Close();
    }

删除固定行的内容

                string[] all = File.ReadAllLines(filePath);
                int deleteRows = 10000;

                if (all.Length > deleteRows)
                {
                    List<string> list = new List<string>(all);

                    for (int i = 0; i < deleteRows; i++)
                    {
                        if (list.Count > 0)
                            list.RemoveAt(0);
                    }

                    File.WriteAllLines(filePath, list.ToArray());
                }
上一篇下一篇

猜你喜欢

热点阅读