Rani Radcliff
Rani Radcliff

Reputation: 5074

CreateDirectory creates Duplicate Directory in Public Folder

I have a Winforms application that is supposed to create a subdirectory in the Public Documents folder if the directory does not exist and save a text file to it. However, if the subdirectory does not exist, it actually creates another directory called Public Documents under "C:/Users/Public" rather than just creating a subdirectory under the existing "C:/Users/Public" folder. (In the example below the subdirectory is the variable 'token'.) So I end up with 2 folders called Public Documents:

enter image description here

Here is my code:

        if (result == DialogResult.Yes)
        {

            subPath = @"C:\Users\Public\Public Documents\" + token + @"\Tests\";

        }
        else if (result == DialogResult.No)
        {
            subPath = @"C:\Users\Public\Public Documents" + @"\Tests\";
        }
        TestModel testCall = new TestModel
        {
            Name = frm.fileName,
            MethodName = txtApiMethod.Text,
            Parameter = rtxtJson.Text,
            SchemaKey = txtSchemaKey.Text
        };
        bool exists = System.IO.Directory.Exists(subPath);
        string fileName = frm.fileName + ".txt";
        string json = JsonConvert.SerializeObject(testCall);
        string filePath = subPath + fileName;
        if (!exists)
        {
            System.IO.Directory.CreateDirectory(subPath);
        }
        using (StreamWriter file = File.CreateText(filePath))
        {
            file.Write(json);

        }

Can someone tell me why it is creating a duplicate named directory, and what I can do to have just create a new subdirectory under the existing directory?

Any assistance is greatly appreciated!

Upvotes: 1

Views: 272

Answers (1)

Cid
Cid

Reputation: 15247

C:\Users\Public\Public Documents is a display name. I have a french Windows, and the display name is C:\Users\Public\Documents publics

The real path is C:\Users\Public\Documents

Display :

Screenshot showing C:\Users\Public\Documents publics as display name

Real :

Screenshot showing C:\Users\Public\Documents as real path

To make sure you are using the correct folder path (for some reasons, d: could be used instead, or the path could be totaly different. Never use hardcoded path), you can use System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments); that links to C:\Users\Public\Documents, such as :

var PublicDocuments = System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonDocuments);
if (result == DialogResult.Yes)
{
    subPath = PublicDocuments + @"\"+ token + @"\Tests\";
}
else if (result == DialogResult.No)
{
    subPath = PublicDocuments + @"\Tests\";
}

See the documentation for more infos about System.Environment.SpecialFolder and System.Environment.GetFolderPath()

Upvotes: 4

Related Questions