Open folder and decide which file to use C#

Sela 126 Reputation points
2022-03-02T15:00:09.843+00:00

Dear Sir or Madam,

I have a question for you. I have a folder with my own generated text files, each with the same extension but with different names. In order to improve the use of the files I would like to open the folder with the programming language C#. the folder and decide which file I would like to use in further processing. Currently the whole thing happens manually by always entering the respective path name, I don't want to solve it that way anymore. (There are always other generated files coming into the folder).
Many thanks in advance.

With kind regards,
Sela

Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-03-02T15:48:02.407+00:00

    I'm not sure I completely follow the problem you're trying to solve but it sounds like you want to select a file in your C# app. You didn't mention what type of app it is but only a Windows UI would allow you to select from a graphical UI. To do that you would use the OpenFileDialog. Something like this.

       private string SelectFile ()  
       {  
          var dlg = new OpenFileDialog() {  
              InitialDirectory = "your default path you want to use, if any",  
              Filter = "Text Files (*.txt) | *.txt | All Files (*.*) | *.*",  
              RestoreDirectory = true        
          };  
         
          //User didn't select a file so return a default value  
          if (dlg.ShowDialog() != DialogResult.OK)  
             return "";  
         
          //Return the file the user selected  
          return dlg.FileName;  
       }  
    

    For a console application you would need to retrieve the files in the directory(ies) you care about and display some sort of menu or something, depending upon what you needed.


1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-03-02T16:49:07.467+00:00

    Going with @Michael Taylor reply, do you want to pre-select a file? If so than consider the following. All I've added was FileName set to whatever file you would want pre-selected and exists.

    var dlg = new OpenFileDialog()  
    {  
        InitialDirectory = "our default path you want to use",  
        Filter = "Text Files (*.txt) | *.txt | All Files (*.*) | *.*",  
        RestoreDirectory = true,   
        FileName = "File to pre select goes here that resides in InitialDirectory"  
    };  
      
    if (dlg.ShowDialog() == DialogResult.OK )  
    {  
        //  
    }  
    else  
    {  
        //  
    }  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.