Friday, May 29, 2009

Easiest way to find file extension from SPFile Object

We can pass SPFile.Name object into FileInfo Class and get the extension of file. It will returns “.ASPX” or “.HTML” file extension depending upon file object.

 Example Code:   

SPFile objFile;

string strFileExtension = new FileInfo(objFile.Name).Extension;

4 comments:

  1. hi,
    good trick but this can also be done with one more way
    recently i was stuck with the same issue and i wanted the filename without extension and not the extension by itself..
    one way was to take the extension and use substring in file name but a tedious way to so..

    so i took the another approach and it was quite simple

    using System.IO;

    string filenamewitoutextension = Path.GetFileNameWithoutExtension(objFile.Name);

    string extension = Path.GetExtension(objFile.Name);

    hope this comes handy...
    Enjoi..........

    ReplyDelete
  2. thanks.it helped me :)

    ReplyDelete
  3. Good trick, but we have to create file info object which may not be desirable all the time.

    We can use SPFile.Item["File Type"] to get extension.

    ReplyDelete
    Replies
    1. Not all items have ["File Type"] field ! Path.GetExtension(objFile.Name) is better.

      Delete