0

filestream用来写一个文本文档。除了文档被定向到错误的文件夹外,一切似乎都运行良好。

这是代码认为它应该创建文档的地方:

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

FedEx管理文件夹中不存在该文件夹。但是,如果我创建一个FedEx文件夹并将其放在该Administration文件夹中,.txt文档就会相应地出现。

这是应该写入文档的文件夹的实际路径:

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

我根本不明白代码是如何工作的以及如何更改它,真的需要一些帮助。

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);
}
4

4 回答 4

2
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);
}
于 2014-01-13T15:50:12.120 回答
2

根据您的陈述,我相信您想要创建这样的路径:

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;

    // this should give me the index at which the "\administration" part of the
    // path starts so we can cut it off
    int index = path.IndexOf("\\administration",
        StringComparison.OrdinalIgnoreCase);

    // when building the path we substring from 0 to the index of the
    // "\administration" part of the string, add "FedEx", the order id,
    // and then finally ".txt"
    string realPath = Path.Combine(path.Substring(0, index), "FedEx",
        orderID.ToString(), ".txt");

    // now open the file
    FileStream file = new FileStream(realPath,
        FileMode.OpenOrCreate,
        FileAccess.Write);
}

此外,Path.Combine这里真的很关键。在构建路径时,在正确的位置上很快就会出现问题\——它可以无缝地处理。

于 2014-01-13T15:50:57.237 回答
0

System.Web.HttpContext.Current.Request.PhysicalPath正在回归,

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

因此,您需要\Administration在附加FedExrealPath.

于 2014-01-13T15:52:17.190 回答
0

你可以把物品放在你想要的任何地方。如果您想对此进行控制,可以使用:

try
{
    Order o = IoC.Resolve<IOrderService>().GetOrderById(orderID);
    Customer ThisCustomer = o.Customer;
    FileStream file = new FileStream("C:/Users/user2/Desktop/work/SuperBy/nop/NopCommerceStore/FedEx/" + orderID.ToString() + ".txt", FileMode.OpenOrCreate, FileAccess.Write);
}

现在更明显的是如何更改代码以使用不同的路径。让任何应该阅读它的人都能阅读您的代码,这一点非常重要。在这种情况下,那就是你自己。

于 2014-01-13T16:03:59.873 回答