如何解决ASP.net中csv文件的附加问题



我在csv文件中添加一些文本时遇到问题,我的文本正在附加,但它正在附加到前一行,而不是新行。我也得到一个类型错误说系统。FormatException:输入字符串的格式不正确。这显然与附加问题有关,但我不明白我在这里做错了什么。有什么想法吗?

这是csv文件中的输出

大学,0

杂货,1

其他,2

游戏,3件套,4

提前感谢:(

控制器

// GET: Category/Create
public ActionResult Create()
{
return View();
}
// POST: Category/Create
[HttpPost]
public ActionResult Create(Category category)
{
try
{
TodolistRepository.AddCategory(category.Name);
return RedirectToAction("Index");
}
catch
{
return View();
}
}

.cs文件

public static bool AddCategory(string category, int catId = 0)
{
int newIdentifier = catId;
if (newIdentifier == 0)
{
int maxIdentifier = _listOfCategories.Max(x => x.Identifier);
newIdentifier = ++maxIdentifier;
}
try
{
using (FileStream fs = new FileStream(_categoriesfile, FileMode.Append, FileAccess.Write))
{
using (var writer = new StreamWriter(fs))
{
var line = $"{category},{newIdentifier.ToString()}";
writer.WriteLine(line);
writer.Flush();
}
}
return true;
}
catch (Exception)
{
return false;
}
}
public static void ReadCategoriesFromFile()
{
using (StreamReader reader = new StreamReader(_categoriesfile))
{
while (!reader.EndOfStream)
{
string[] fields = reader.ReadLine().Split(',');
_listOfCategories.Add(new Category
{
Name = fields[0],
Identifier = Int32.Parse(fields[1])
});
}
}
}
//Gets all the categories in the List
public static List<Category> GetCategories()
{
ReadCategoriesFromFile();
_listOfCategories = _listOfCategories.OrderBy(x => x.Identifier).ToList();
return _listOfCategories;
}

在添加Category的行末尾添加换行符"\r\n"。如果您想检查是否有一行没有换行符,请先读取行。

最新更新