Get all filenames in a directory, without path information - CSharp System.IO

CSharp examples for System.IO:File Path

Description

Get all filenames in a directory, without path information

Demo Code


using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//from w  ww  .j a v  a 2 s  . c om

public class Main{
        public static string[] GetFileNames(string path, bool fileNamesWithoutExtension = false)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentOutOfRangeException("path");
            }

            IList<string> files = new List<string>();

            foreach (var file in System.IO.Directory.GetFiles(path))
            {
                if (!fileNamesWithoutExtension)
                {
                    files.Add(System.IO.Path.GetFileName(file));
                }
                else
                {
                    files.Add(System.IO.Path.GetFileNameWithoutExtension(file));
                }
            }

            return files.ToArray();
        }
}

Related Tutorials