本节没有什么技术含量。权当做给新手做个demo吧。
1 写入text
2追加text
3读取text
4删除文件
@{
View.Title = "File1";
Layout = "~/Views/Shared/_Layout.cshtml";
var path = Server.MapPath("~/App_Data/testdata.txt");
string[] data = null;
//判断是否存在
if (File.Exists(path)) {
//读取text
data = File.ReadAllLines(path);
//追加text
var text2 = "AppendAllText to txt success!" + DateTime.Now + Environment.NewLine;
File.AppendAllText(path, text2);
} else {
//写入
var text1 = "write to txt success!" + DateTime.Now + Environment.NewLine;
//覆盖
File.WriteAllText(path, text1);
}
//删除
if (!Request["action"].IsEmpty()) {
if (Request["action"].ToString() == "delete") {
File.Delete(path);
}
}
}
<h2>
向TXT文件里写东西<br />
@{
}
@if (data != null) {
foreach (var item in data) {
@item <br />
}
}
</h2>
<a href="?action=delete">delete</a>
Layout = "~/Views/Shared/_Layout.cshtml";
var path = Server.MapPath("~/App_Data/testdata.txt");
string[] data = null;
//判断是否存在
if (File.Exists(path)) {
//读取text
data = File.ReadAllLines(path);
//追加text
var text2 = "AppendAllText to txt success!" + DateTime.Now + Environment.NewLine;
File.AppendAllText(path, text2);
} else {
//写入
var text1 = "write to txt success!" + DateTime.Now + Environment.NewLine;
//覆盖
File.WriteAllText(path, text1);
}
//删除
if (!Request["action"].IsEmpty()) {
if (Request["action"].ToString() == "delete") {
File.Delete(path);
}
}
}
<h2>
向TXT文件里写东西<br />
@{
}
@if (data != null) {
foreach (var item in data) {
@item <br />
}
}
</h2>
<a href="?action=delete">delete</a>
5上传文件
@{
View.Title = "File2";
Layout = "~/Views/Shared/_Layout.cshtml";
var uploadfile = Request.Files["uploadfile"];
if (uploadfile != null) {
var filename = Path.GetFileName(uploadfile.FileName);
string filepath = Server.MapPath("~/Content/" + filename);
uploadfile.SaveAs(filepath);
@uploadfile.FileName
<a href="@Href("~/Content/" + filename)">上传的文件</a>
}
}
View.Title = "File2";
Layout = "~/Views/Shared/_Layout.cshtml";
var uploadfile = Request.Files["uploadfile"];
if (uploadfile != null) {
var filename = Path.GetFileName(uploadfile.FileName);
string filepath = Server.MapPath("~/Content/" + filename);
uploadfile.SaveAs(filepath);
@uploadfile.FileName
<a href="@Href("~/Content/" + filename)">上传的文件</a>
}
}
<h2>
上传
</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile" />
<input type="submit" value="UpLoad" />
</form>
上传
</h2>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile" />
<input type="submit" value="UpLoad" />
</form>
通常我们不会把文件操作写到“轻快的view”里。我这里只是演示可以实现这些功能。其用到的都是大家熟悉的file等类。