File Extension - C #

I have a directory that contains jpg, tif, pdf, doc and xls. The client database console contains file names without an extension. My application should pick up the file and upload the file. One of the properties of the upload object is the file extension.

Is there a way to get the file extension if I have the path and name

eg:

C: \ temp \ somepicture.jpg is the file and the information I get through db,

C: \ Temp \ somepicture

+3
source share
11 answers

You can get a list of all files with this name, regardless of the extension:

public string[] GetFileExtensions(string path)
{
    System.IO.DirectoryInfo directory = 
        new System.IO.DirectoryInfo(System.IO.Path.GetDirectoryName(path));

    return directory.GetFiles(
        System.IO.Path.GetFileNameWithoutExtension(path) + ".*")
        .Select(f => f.Extension).ToArray();
}
0
source

Directory.GetFiles(fileName + ".*"). , . , , .

+5

- :

DirectoryInfo D = new DirectoryInfo(path);
foreach (FileInfo fi in D.GetFiles())
{
    if (Path.GetFileNameWithoutExtension(fi.FullName) == whatever)
        // do something
}
+3

, , 2 , (, somepicture.jpg somepicture.png).

, , (, somepicture. *), ( ) .

0

somepicture. * , ?

0

. : 'C:\Temp \'

, , : 'Somepicture'

, . , .

0

System.IO.Directory.GetFiles() . , somefile.jpg somefile.tif.

, , , , .

0

- , ....

    DirectoryInfo di = new DirectoryInfo("c:/temp/");
    FileInfo[] rgFiles = di.GetFiles("somepicture.*");
    foreach (FileInfo fi in rgFiles)
    {
        if(fi.Name.Contains("."))
        {
            string name = fi.Name.Split('.')[0].ToString();
            string ext =  fi.Name.Split('.')[1].ToString();

            System.Console.WriteLine("Extension is: " + ext);
        }
    }
0

, , , .

string[] files = Directory.GetFiles(@"c:\temp", @"testasdadsadsas.*");

if (files.Length >= 1)
{
    string fullFilenameAndPath = files[0];

    Console.WriteLine(fullFilenameAndPath);
}
0

:

string path = Path.GetDirectoryName(filename);
string name = Path.GetFileName(filename);

, , :

FileInfo[] found = new DirectoryInfo(path).GetFiles(name + ".*");

, . , , , .

0

, - " " , , FirstOrDefault, .

static void Main(string[] args)
{
    var match = FindMatch(args[0]);
    Console.WriteLine("Best match for {0} is {1}", args[0], match ?? "[None found]");
}

private static string FindMatch(string pathAndFilename)
{
    return FindMatch(Path.GetDirectoryName(pathAndFilename), Path.GetFileNameWithoutExtension(pathAndFilename));
}

private static string FindMatch(string path, string filename)
{
    return Directory.GetFiles(path, filename + ".*").FirstOrDefault();
}

:

> ConsoleApplication10 c:\temp\bogus
Best match for c:\temp\bogus is [None found]
> ConsoleApplication10 c:\temp\7z465
Best match for c:\temp\7z465 is c:\temp\7z465.msi
> ConsoleApplication10 c:\temp\boot
Best match for c:\temp\boot is c:\temp\boot.wim
0

Source: https://habr.com/ru/post/1735297/


All Articles