在我的 ASP.NET MVC 项目中,我在名为 data 的文件夹中有一个名为 name.txt 的文本文件。我想写信给它,但我很难引用它。我的尝试:
string path = Path.Combine(Environment.CurrentDirectory, @"data/", name + ".txt");
StreamWriter file = new StreamWriter(path);
file.WriteLine("Write something in file");
file.Close();
不幸的是,我收到的错误是路径不存在。有没有一种简单易行的方法来获取 ASP.NET 项目中文件夹的文件路径?
谢谢
答案 0 :(得分:1)
我认为您正在寻找这样的东西,
Cypress.Commands.add('onReduxAction', actionType => {
const promise = new Cypress.Promise(resolve => {
cy.on('emit:reduxAction', ({action}) => {
if (action.type === actionType) {
resolve(action.type);
}
});
});
return { promise }
});
cy.onReduxAction('MY_ACTION').then(promiseWrapper => { // Cypress then method
promiseWrapper.promise.then(data => { // Promise then method
// some logic
})
});
cy.visit('');
请注意,string path = Path.Combine(Environment.CurrentDirectory, @"data/", name + ".txt");
using (StreamWriter file = new StreamWriter(path))
{
file.Write("Write something on file");
}
file.Close();
将在您第二次尝试时失败,因此您可能需要查看 @Danny Tuppeny 提供的解决方案 how to create .txt file and write it c# asp.net
问候,
乔伊
答案 1 :(得分:0)
两件事。
在 ASP.NET Core 中,您需要从 localhost/path/static/media/icon...png
界面检索应用程序运行所在的路径。在下面的代码中,您将在构造函数中看到它使用依赖注入来访问它。
它有两个属性,
IWebHostEnvironment
是应用程序的根目录ContentRootPath
是 wwwroot 文件夹同样为了简化事情,我重构了使用 WebRootPath
写入文件的内容,File.WriteAllText()
是 StreamWriter 的一个新的便利包装器,并且完全按照答案中显示的方式进行操作。
最后一件事是个人喜好,我选择了字符串插值 $""
而不是与 +
连接。
public class FileSystemFileController : Controller
{
private readonly IWebHostEnvironment webHostEnvironment;
public FileSystemFileController(IWebHostEnvironment webHostEnvironment)
{
this.webHostEnvironment = webHostEnvironment;
}
public IActionResult Index(string name)
{
string path = Path.Combine(webHostEnvironment.ContentRootPath, $"data/{name}.txt");
System.IO.File.WriteAllText(path, "Write something on file");
return View();
}
}