Search code examples
c#xmldocumentpath-combine

Saving file into Path.Combine directory


Could someone advise of how can I save a file into Path.Combine directory? Please find some of my code below.

Creation of directory:

string wholesalePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
Directory.CreateDirectory(wholesalePath);

I have also specified a file name which should be used.

 string fileName = "xmltest.xml";

Then I have re-created a "wholesalePath" to include file name:

wholesalePath = Path.Combine(wholesalePath, fileName);

Few simple lines of code that gets executed:

        XmlDocument doc = new XmlDocument();
        string oneLine = "some text";
        doc.Load(new StringReader(oneLine));
        doc.Save(fileName);
        Console.WriteLine(doc);

The problem I am having is that when I use doc.Save(fileName)then I am getting file in VisualStudio project directories which is wrong directory.

However when I am using doc.Save(wholesalePath)then file that should be created "xmltest.xml" is actually created as another directory within "wholesalePath".

I would be grateful for any suggestions.


Solution

  • As said in the comments, you need to use wholesalePath to create the directory before appending fileName. You need to use wholesalePath after appending fileName to save the file. I tested the following code and it works as expected:

    void Main()
    {
        string mainFolder = "StackOverflow";
        string wholesaleFolder = "Test";
        string wholesalePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
        Directory.CreateDirectory(wholesalePath);
        string fileName = "xmltest.xml";
        wholesalePath = Path.Combine(wholesalePath, fileName);
        XmlDocument doc = new XmlDocument();
        string oneLine = "<root></root>";
        doc.Load(new StringReader(oneLine));
        doc.Save(wholesalePath);
    }
    

    It creates a file named xmltest.xml in a desktop folder named StackOverflow\Test.

    That will work, but I would recommend creating separate variables for the folder and the file path. This will make the code clearer, since each variable will only have one purpose, and will make such errors less likely. For example:

    void Main()
    {
        string mainFolder = "StackOverflow";
        string wholesaleFolder = "Test";
        string fileName = "xmltest.xml";
        string destinationFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), mainFolder, wholesaleFolder);
        string destinationFilePath = Path.Combine(destinationFolder, fileName);
    
        Directory.CreateDirectory(destinationFolder);
        XmlDocument doc = new XmlDocument();
        string oneLine = "<root></root>";
        doc.Load(new StringReader(oneLine));
        doc.Save(destinationFilePath);
    }