C#常用IO操作


文件夾

創建文件夾

//如果文件夾路徑不存在則創建文件夾
if (!Directory.Exists(path))
    Directory.CreateDirectory(path);

遞歸創建文件夾

        public void createdir(string fullpath)
        {
            if (!File.Exists(fullpath))
            {
                string dirpath = fullpath.Substring(0, fullpath.LastIndexOf('\\'));
                //string[] pathes = dirpath.Split('\\');
                string[] pathes = fullpath.Split('\\');
                if (pathes.Length > 1)
                {
                    string path = pathes[0];
                    for (int i = 1; i < pathes.Length; i++)
                    {
                        path += "\\" + pathes[i];
                        //如果文件夾路徑不存在則創建文件夾
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);
                    }
                }
            }
        }
View Code

刪除整個文件夾

Directory.Delete(path, true)

 獲取目錄下的文件(夾)

            var list = new string []{ };
            string path = @"D:\公司SVN";
            //獲取路徑下所有文件
            list = Directory.GetFiles(path);
            //獲取路徑下所有文件夾
            list = Directory.GetDirectories(path);
            //獲取路徑下所有文件+文件夾
            list = Directory.GetFileSystemEntries(path);
            //獲取路徑下所有文件(包含子集文件)
            list = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
            //獲取路徑下所有文件夾(包含子集文件夾)
            list = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
            //獲取路徑下所有文件+文件夾(包含子集文件+子集文件夾)
            list = Directory.GetFileSystemEntries(path, "*.*", SearchOption.AllDirectories);

 

文件

 

獲取文件全路徑、目錄、擴展名、文件名稱

class Program
    {
        static void Main(string[] args)
        {

            //獲取當前運行程序的目錄
            string fileDir = Environment.CurrentDirectory;
            Console.WriteLine("當前程序目錄:"+fileDir);

            //一個文件目錄
            string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml";
            Console.WriteLine("該文件的目錄:"+filePath);

            string str = "獲取文件的全路徑:" + Path.GetFullPath(filePath);   //-->C:\JiYF\BenXH\BenXHCMS.xml
            Console.WriteLine(str);
            str = "獲取文件所在的目錄:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH
            Console.WriteLine(str);
            str = "獲取文件的名稱含有后綴:" + Path.GetFileName(filePath);  //-->BenXHCMS.xml
            Console.WriteLine(str);
            str = "獲取文件的名稱沒有后綴:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS
            Console.WriteLine(str);
            str = "獲取路徑的后綴擴展名稱:" + Path.GetExtension(filePath); //-->.xml
            Console.WriteLine(str);
            str = "獲取路徑的根目錄:" + Path.GetPathRoot(filePath); //-->C:\
            Console.WriteLine(str);
            Console.ReadKey();

        }
    }

 

 

創建文件

            //path是完整路徑,要包含文件的后綴名
            string path = @"C:\1.txt";
            //判斷文件是否存在,不存在就創建
            if (!File.Exists(path))
            {

                //創建一個 UTF-8 編碼text文件
                File.CreateText(path);


                //創建一個文件
                //File.Create(path);
            }

 寫入文件

using System.IO;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            //寫入文本,不是追加,是清空在寫入
            string path = @"C:\1.txt";
            string[] lines = { "First line", "Second line", "Third line" };
            File.WriteAllLines(path, lines);
            File.WriteAllText(path, "AAAAAAAAAAAAAAAA");

            //追加寫入文本
            using (StreamWriter sw = new StreamWriter(path, true))
            {
                sw.WriteLine("Fourth line");
            }
            using (StreamWriter sw = File.AppendText(path))
            {
                sw.Write(12345);
            }

        }
    }
}

 

文件流讀寫

        public Stream FileToStream(string fileFullName)
        {
            using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
            {
                byte[] bytes = new byte[fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                return new MemoryStream(bytes);
            }
        }

        public void WriteFile(string fileFullName, byte[] bytes)
        {
            if (bytes == null)
                return;
            using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
            {
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();
            }

            #region 第二種
            /*
                using (MemoryStream m = new MemoryStream(bytes))
                using (FileStream fs = new FileStream(fileFullName, FileMode.OpenOrCreate))
                {
                    m.WriteTo(fs);
                }
             */
            #endregion

        }

 

 

Stream 和 byte[] 互轉

        /// <summary>
        /// 將 Stream 轉成 byte[]
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public byte[] StreamToBytes(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Seek(0, SeekOrigin.Begin);
            stream.Flush();
            stream.Close();
            return bytes;

        }

        /// <summary>
        /// 將 byte[] 轉成 Stream
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public Stream BytesToStream(byte[] bytes)
        {
            return new MemoryStream(bytes);
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM