Search code examples
c#create-directory

Question about File Paths and opening those files C#


I have Three strings that are set to the current: year, month, day respectively using the "DateTimeNow". and I have set a path to a string of the root folder named "Custom_project" by grabbing the file path from a text file on the desktop.

They are named:

public string CurrentYear;
public string CurrentMonth;
public string CurrentDay;
public string CustomOrderFilePathTopFolder = File.ReadAllText("C:/desktop/Custom_project.txt");
//CustomOrderFilePathTopFolder now ='s C:/desktop/Custom_project/

Okay so I am trying to check to see if a folder exists(Folder Named: "CurrentYear" or in this case "2020" inside of the: "Custom_project" folder) and if not then create the folder with the string, if it does exist then it will then proceed to my next step which is essentially opening the file: "CurrentYear" or "2020, then repeating the same thing but inside of that folder: Custom_project/2020, for month and repeat one last time for day.

So In the end I would have a file path that looks like so: "C:/desktop/Custom_project/2020/07/12".

Now To My Question: "HOW DO I GO ABOUT CHECKING IF A FILE NAMED "2020" EXISTS INSIDE OF THE CUSTOMPATHFOLDER AND IF IT DOESN'T THEN CREATE THAT FOLDER

I just tried using This(Which doesn't seem to work):

        if (CustomOrderFilePathTopFolder == "")
        {
            MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
        }
        else if (!Directory.Exists(CustomOrderFilePathTopFolder + CurrentYear))
        {
            Directory.CreateDirectory(CustomOrderFilePathTopFolder + CurrentYear);
        }

This Does nothing for me so I tried this:

        if (CustomOrderFilePathTopFolder == "")
        {
            MessageBox.Show("ERROR FILE PATH CANNOT BE EMPTY!");
        }
        else if (!Directory.Exists(CustomOrderFilePathTopFolder + "/" + CurrentYear))
        {
            Directory.CreateDirectory(CustomOrderFilePathTopFolder + "/" + CurrentYear);
        }

Doesn't Work Either So I am At a loss Please Let me know how I would go about this please and thank you a ton!!


Solution

  • Try below steps

    • you need to first combine path to point proper file/folder

    • Check File exists or not

    • If not, then create folder with same name.

      using System.IO;
      ...
      
      var filePath = Path.Combine(CustomOrderFilePathTopFolder, CurrentYear))
      if (!File.Exists(filePath))
      {
          Directory.CreateDirectory(filePath);
      }