views:

136

answers:

3

Hi. I'm want to do a class with file extensions, I thought the extensions should be strings. My problem is I'm not sure how to do this class? I want it to be kinda static so I don't have to declare it like new. I would appreciate any help I can get on this, it's often I find myself in situations where I would need a class like this.

EDIT

I'm trying to do a class that got a List or just a string[] with different extensions, like ".png", ".jpg" ect as a list. so I can later on in my Controller check if the file input has one of those extensions that are "valid".

Not really a reason to down vote -3 for this and there are acutually people who got the question and there are valid answers so if you want to close this fine. let me just get the code.

EDIT CODE
I later on just use the file extension from the file and check if this list contain it. Simple for pice of code most think but helpful for newbies and its actually pretty handy instead of writing the fileExt != ".png" ect all the time.

public static class FileExtensionsPicture
{
    public static List<string> ExtensionList = new List<string> { ".png", ".jpg" };
}

Thanks

+2  A: 

There's no such thing as kinda static in .NET. You have three possibilities: a static class, a normal class with instance methods and an extension method to the string type. For string extension:

public static class StringExtensions
{
    public static void Foo(this string value)
    {
    }

    public static void Bar(this string value)
    {
    }
}

which could be used like this:

"abc".Foo();

assuming you've brought the extension method in scope.

Darin Dimitrov
+1  A: 

Assuming that you are trying to get the extension from a file name, have a look at the Path.GetExtension method.

Paolo Tedesco
+5  A: 
public static class FileExtensions
{
 public static readonly string Pdf = "pdf";
 public static readonly string Text = "txt";
}

an alternative if you need more granular FileExtensions might be:

public static class FileExtensions
{
 public static class Images
 {
  public static readonly string Jpeg = "jpg";
 }
}

this could then be used like this:

FileExtensions.Pdf

OR

FileExtensions.Images.Jpeg

EDIT: Here's a slightly different way in which more data could be stored for each filetype

public class FileTypes
{
 public static readonly Pdf = new FileTypes("pdf", "Adobe Acrobat");
 public static readonly Excel = new FileTypes("xls", "Microsoft Excel");

 private FileTypes(string extension, string programName)
 {
  Extenssion = extension;
  ProgramName = programName;
 }

 public string Extension { get; private set; }
 public string ProgramName { get; private set; }
}

this can then be used like this:

FileTypes.Excel.Extension
FileTypes.Excel.ProgramName
saret
exactly what I needed thanks m8
Dejan.S
You might want to include the leading `.`, because the `Path` class keeps it, too.
Steven Sudit