C# 获取文件夹里所有文件名

主要是这个方法

        List<string> GetAllFileNames(string path,string pattern="*")
        {
            List<FileInfo> folder  = new DirectoryInfo(path).GetFiles(pattern).ToList();

            return folder.Select(x=>x.Name).ToList();
        }
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GetFileNames
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            textBox1.Text = @"D:\jdScript\jdpro-main";
            textBox2.Text = "*.js";
        }

        string _outFileName = "aaaa.bat";

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (var fileName in GetAllFileNames(textBox1.Text))
            {
                richTextBox1.AppendText("node " + fileName + '\n');
            }

            OutputFile(textBox1.Text + "\"+ _outFileName, richTextBox1.Text);
        }

        void OutputFile(string strFilePath,string strContent)
        {
            StreamWriter swOut = new StreamWriter(strFilePath, false, Encoding.Default);
            swOut.WriteLine(strContent);
            swOut.Flush();
            swOut.Close();
        }

        List<string> GetAllFileNames(string path,string pattern="*")
        {
            List<FileInfo> folder  = new DirectoryInfo(path).GetFiles(pattern).ToList();

            return folder.Select(x=>x.Name).ToList();
        }

    }
}

带多项筛选功能

        private static IEnumerable<string> GetFilesNames(string path, string extensions)
        {
            string[] tmp = extensions.Split('|');

            return new DirectoryInfo(path).GetFiles("*").Select(x => x.Name)
             .Where(f => extensions.Contains(Path.GetExtension(f).ToLower()));
        }

调用

List<string> lis = GetFilesNames("./DataBase", ".db|.mdf").ToList();

你可能感兴趣的:(C#,C#,winform,c#,开发语言)