简体   繁体   中英

saving text to a file

I have a question that's driving me nuts. I have a program that saves error messages to a string in an object, then writes the string to a file in the unloadContent() thing. For some reason I keep getting Not Supported Exceptions. Here is the code in 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");
        }

and here's the code in class save errors:

    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();
            }
        }
    }

I'm still a bit new to C#, so any help would be greatly appreciated!

Thanks!

Try this:

[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);       
}

To get the DateTime.ToString() in the desired format you can pass a formatstring

save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\\\Errors\\\\errorLog_" + (System.DateTime.Now.ToString().Replace("/", "_")).Replace(" ", "").Replace(":", "") + ".txt");

Change it to that. You need a .Replace(":", "") because : Is included in the date part of the code, but is invalid in a file name, so you must either remove it or replace it with something else.

As an alternative you could format the date as so:

save.save(System.IO.Directory.GetCurrentDirectory().ToString() + "\\\\Errors\\\\errorLog_" + System.DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM