none
C# Class Question RRS feed

  • Question

  • It's been a while since I've written c# code so I'm a bit rusty. I need a quick refresher course on how to write and use a class. The code I'm using works great but it's all in a single file, Program.cs and in order to make this thing compliant with OOP I want to move the parts of it to their own class. The first task I need to handle is to set the value for a string array which will hold a list of all the *.pdf files in a folder.

    string[] filelist = new GetFiles();
    

    Here is the class as I have it now...

    public class GetFiles { public GetFiles() { DirectoryInfo dirInfo = new DirectoryInfo(@"C:\MyFolder\"); FileInfo[] fileInfos = dirInfo.GetFiles("*.pdf"); ArrayList list = new ArrayList(); foreach (FileInfo info in fileInfos) { // HACK: Just skip the protected samples file... if (info.Name.IndexOf("protected") == -1) list.Add(info.FullName); }

    }

    What I'd like to do is to have the class use an object which I can run through other parts of the code, but it's been so long since I last wrote code in C#. Any advice would be appreciated.

    Wednesday, January 9, 2019 5:24 PM

All replies

  • Hi,

    public GetFiles() is the constructor. You should implement a method for this:

    public class GetFiles { public ArrayList Get(string path) { DirectoryInfo dirInfo = new DirectoryInfo(path); FileInfo[] fileInfos = dirInfo.GetFiles("*.pdf"); ArrayList list = new ArrayList(); foreach (FileInfo info in fileInfos) { // HACK: Just skip the protected samples file... if (info.Name.IndexOf("protected") == -1) list.Add(info.FullName); } return list;

    } }


    And use it like this:

    var getFiles = new GetFiles();
    var filelist = getFiles.Get(@"c:\MyFolder\");

    Greetings, Chris



    • Edited by DerChris88 Wednesday, January 9, 2019 6:29 PM
    Wednesday, January 9, 2019 6:19 PM
  • Thanks Chris,

    I think I'm finding my problem. There is a built-in class to VS2017 which is called Directory.GetFiles. Trouble with trying to learn coding on the net is that so many different people showing different methods and perhaps the original code I used was authored before this class was added to the stack. I may be wrong about this but believe me, as someone who is self-taught on just about every computer skill I use, there is loads of bad, old information and mis-information all over the place.

    Wednesday, January 9, 2019 6:44 PM
  • I don't understand your question...

    Do you mean this static method of the class Directory?

    var files = Directory.GetFiles("c:\\folder\\");
    What is your goal? You want to split your code in more than one class? Really? Why that? Instead of calling new in your method you could use parameters...
    Wednesday, January 9, 2019 7:39 PM