Search code examples
c#pathsubstringfilestreamlastindexof

How do i change path to folder location when writing a .txt document?


I'm using filestream to write a text document. Everything seems to work fine except that the document is directed to the wrong folder.

This is where the code thinks it should create the document:

C:\Users\user2\Desktop\work\SuperBy\nop\NopCommerceStore\Administration\FedEx

The FedEx folder dosn't exist in the Administration folder. But if I create a FedEx folder and place it in the Administration folder, the .txt documents appear accordingly.

This is the actual path do the folder in which the documents should be written:

C:\Users\user2\Desktop\work\SuperBy\nop\NopCommerceStore\FedEx

I simply don't understand how the code works and how to change it, really need some help with this.

try
{
    Order o = IoC.Resolve<IOrderService>().GetOrderById(orderID);
    Customer ThisCustomer = o.Customer;

    // Specify file, instructions, and privelegdes
    string path = System.Web.HttpContext.Current.Request.PhysicalPath;
    int index = path.LastIndexOf("\\");
    string realPath = path.Substring(0, index + 1);
    FileStream file = new FileStream(realPath + "/FedEx/" + orderID.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
}

Solution

  • try
    {
        Order o = IoC.Resolve<IOrderService>().GetOrderById(orderID);
        Customer ThisCustomer = o.Customer;
    
        // Specify file, instructions, and privelegdes
        string path = System.Web.HttpContext.Current.Request.PhysicalPath;
        int index = path.LastIndexOf("\\");
        string realPath = path.Substring(0, index + 1);
        FileStream file = new FileStream(realPath + "/../FedEx/" +
            orderID.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
    }