文件和文件夹的操作——文件操作

举报
AI浩 发表于 2021/12/23 00:32:01 2021/12/23
【摘要】 操作文件夹的类:Directory,需要引用的命名空间:using System.IO; 例: class Program     {         static void Main(string[] args)  ...

操作文件夹的类:Directory,需要引用的命名空间:using System.IO;

例:

class Program

    {

        static void Main(string[] args)

        {

            String str=@"D:\temp";

            Directory.CreateDirectory(str);//创建文件夹

            if (Directory.Exists(str))//判断是否存在

            {

                Console.WriteLine("存在temp文件夹");

            }

            Directory.Delete(str);//删除文件夹

        }

}

获取文件夹下的所有文件:

static void Main(string[] args)

        {

            string[] files = Directory.GetFiles("D:\\360驱动大师目录\\驱动备份目录");

            foreach (string file in files)//去除文件的路径

            {

                int idx = file.LastIndexOf(@"\");

                string temp = file.Substring(idx + 1, file.Length - idx - 1);

                Console.WriteLine(temp);

            }

            foreach (string file in files)//显示文件的路径

            {

                Console.WriteLine(file);

            }

        }

使用FileInfo类获取文件信息:

string[] files = Directory.GetFiles("D:\\360驱动大师目录\\驱动备份目录");

            foreach (string file in files)//去除文件的路径

            {

                FileInfo info = new FileInfo(file);

                string tmp = info.Name;

                Console.WriteLine(tmp+"  "+info.Length/1024);

            }

获取文件夹中子目录的名字:

   string[] dirs = Directory.GetDirectories("D:\\360驱动大师目录");

            foreach (string dir in dirs)

            {

                Console.WriteLine(dir);

            }

File文件类。

创建文件用:File.Create(@"D:\ite.txt");

复制文件:File.Copy(@"D:\ite.txt", @"E:\aa.txt");

删除文件:File.Delete;

剪贴文件:File.More;

判断文件是否存在:File.Exists;

创建一个文件并向里面填写内容:

   FileStream fs = new FileStream(@"D:\ite.txt", FileMode.OpenOrCreate);

   StreamWriter writer = new StreamWriter(fs);

   writer.WriteLine("uhuirhiuheriuhiuerhiu");

   writer.Close();

   fs.Close();

读取文件的内容:

FileStream fs = new FileStream(@"D:\ite.txt", FileMode.OpenOrCreate);

StreamReader reader = new StreamReader(fs);

string line = "";

while ((line = reader.ReadLine()) != null)

{

Console.WriteLine(line);

}

reader.Close();

fs.Close();

对二进制文件的写操作:

FileStream fs = new FileStream(@"D:\it.txt", FileMode.OpenOrCreate|FileMode.Append);//打开创建或追加

            BinaryWriter writer = new BinaryWriter(fs);

            writer.Write("asgdiufhdsaiuhfoiuahss");

            writer.Close();

            fs.Close();

对二进制文件的读操作:

FileStream fs = new FileStream(@"D:\it.txt", FileMode.OpenOrCreate|FileMode.Append);//打开创建或追加

            BinaryReader reader = new BinaryReader(fs);

            char[] bt = new char[fs.Length];

            reader.Read(bt, 0, (int)fs.Length);

            string aa = new string(bt);

            Console.WriteLine(aa);

            reader.Close();

            fs.Close();

 

 

 

例:多线程删除文件和文件夹(使用于大数量的文件和文件夹)

using System;

uploading.4e448015.gif转存失败重新上传取消using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

using System.Threading;

namespace DeleteDir

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        /// <summary>

        /// 选择按钮 选择要删除的文件夹

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnSelect_Click(object sender, EventArgs e)

        {

            FolderBrowserDialog fbdDialog = new FolderBrowserDialog();//创建FolderBrowserDialog对象

            if (fbdDialog.ShowDialog() == DialogResult.OK)

            {

                txtPath.Text = fbdDialog.SelectedPath;

            }

        }

        private void btnDel_Click(object sender, EventArgs e)

        {

            DirectoryInfo dirInfo = new DirectoryInfo(txtPath.Text.Trim());

            DirectoryInfo[] dirAtt = dirInfo.GetDirectories();//获取文件夹下所有的文件夹

            int dirAttLength = dirAtt.Length;

            for (int i = 0; i < dirAttLength; i++)

            {

                Thread[] that = new Thread[dirAttLength];

                DirDelete dt = new DirDelete();

                dt.DicInfo = dirAtt[i];

                that[i] = new Thread(dt.Delete);

                that[i].Name = "th" + i;

                that[i].IsBackground = true;

                that[i].Start();

            }

            if (dirAtt.Length == 0)

            {

                DirDelete dt = new DirDelete();

                dt.DicInfo = dirInfo;

                Thread that = new Thread(dt.Delete);

                that.IsBackground = true;

                that.Start();

            }

        }

    }

    public class DirDelete {

        public DirectoryInfo DicInfo { get; set; }

        public void Delete()

        {

            DeleteFileAndDirectory(DicInfo);

        }

        private void DeleteFileAndDirectory(DirectoryInfo info)

        {

            if (info.Exists == false){return;}

            DirectoryInfo[] childDir=info.GetDirectories();

            foreach (DirectoryInfo newInfo in childDir)

            {

                DeleteFileAndDirectory(newInfo);

            }

            foreach (FileInfo file in info.GetFiles())

            {

                if (file.Exists)

                {

                    file.Attributes = FileAttributes.Normal;//防止文件受保护不能删除

                    file.Delete();

                }

            }

            if (info.Exists)

            {

                info.Attributes = FileAttributes.Normal;

                info.Delete();

            }

        }

    }

}

文章来源: wanghao.blog.csdn.net,作者:AI浩,版权归原作者所有,如需转载,请联系作者。

原文链接:wanghao.blog.csdn.net/article/details/105593619

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。