我有一个让我疯狂的问题。我有一个程序将错误消息保存到对象中的字符串,然后将该字符串写入unloadContent()事件中的文件。出于某种原因,我一直得到不支持的例外。这是unloadContent()中的代码:
if (debug.getContent().Length > 0)
{
saveErrors save = new saveErrors();
if (Directory.Exists(System.IO.Directory.GetCurrentDirectory() + "\\Errors")) ;
Directory.CreateDirectory(System.IO.Directory.GetCurrentDirectory() + "\\Errors");
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ","") + ".txt");
}
这是类中保存错误的代码:
public class saveErrors
{
private string mess = debug.getContent();
public void save(string fileName)
{
Debug.WriteLine(fileName);
using (StreamWriter sw = new StreamWriter(fileName))
{
sw.Write(mess);
sw.Close();
}
}
}
我对C#还是有点新鲜,所以任何帮助都将不胜感激!
谢谢!
答案 0 :(得分:3)
试试这个:
[Test]
public void SaveTextTest()
{
string relativePath=@"Errors\errorLog_";
string directoryPath = System.IO.Path.Combine( System.IO.Directory.GetCurrentDirectory() , relativePath);
var directoryInfo = new DirectoryInfo(directoryPath);
if(directoryInfo.Exists==false)
directoryInfo.Create();
string fileName = System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") + ".txt";
string path = System.IO.Path.Combine(directoryPath, fileName);
string textToSave = "This will be saved";
File.WriteAllText(path, textToSave);
}
要获得所需格式的DateTime.ToString(),您可以传递formatstring
答案 1 :(得分:1)
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ", "").Replace(":", "") + ".txt");
将其更改为。您需要.Replace(":", "")
,因为:
包含在代码的日期部分中,但在文件名中无效,因此您必须将其删除或替换为其他内容。
作为替代方案,您可以将日期格式化为:
save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\Errors\\errorLog_" + System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));