c# - 将文本保存到文件

标签 c# file stream

我有一个让我抓狂的问题。我有一个程序将错误消息保存到对象中的字符串,然后将字符串写入 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# 还是有点陌生​​,所以非常感谢任何帮助!

谢谢!

最佳答案

试试这个:

[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

关于c# - 将文本保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12764698/

相关文章:

java - 如何在运行时加载的 jsp 中包含 html 片段?

join - 在 Apache Flink 中合并两个流,无论窗口时间如何

c# - 在 Xamarin Forms 中从 ViewModel 绑定(bind) MasterDetailPage

python - 从非常大的文件中删除稀有词

c# - 将 DataGrid 导出到 CSV 或 Excel

ios - Swift - 导入和打开自定义文件扩展名

node.js - 重用写入流而不结束它并一遍又一遍地声明新流

objective-c - NSNetServiceBrowser didRemoveService 在打开流后需要更长的时间

c# - 终结器和处置

c# - C#模板化结构: Cannot implicitly convert