繁体   English   中英

每当我尝试使用此方法时,“ mscorlib.dll中出现类型'System.IO.IOException'的未处理的异常”

[英]“An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll” whenever I try using this method

public void SaveAll(int volume, int duration, string playing, int 
                        LBPindex, int LBSindex, string URL, int maximum)
{
    FileStream fs = new FileStream("SaveDATA.bin", FileMode.Create);
    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
    sw.WriteLine("SETTINGS" + "|" + volume + "|" + duration + "|" + 
    playing + "|" + LBPindex + "|" + LBSindex + "|" + URL + "|" + 
    maximum);

    foreach (var item1 in Playlist.SavedPlaylists)
    {
        sw.Write("PLAYLIST" + "|" + item1.Name + "|");
        foreach (var item2 in item1.SavedSongs)
        {
            sw.WriteLine(item2.Path + "|" + item2.Title + "|" + 
            item2.Author + "|" + item2.Album + "|" + item2.Release + 
            "|" + item2.Genre + "|" + item2.Comment);
        }
    }
    sw.Close();
    fs.Close();
}

我正在制作音乐播放器,并且每次用户将某些内容更改为播放列表,歌曲或任何内容时,都会使用此方法。

每当我的Filestream尝试执行某项操作时,都会发生该错误。

您不会处置FileStreamStreamWriter 因此,他们可能会坚持某些东西……特别是如果引发异常。

将它们都using块包装。

从技术上讲,StreamWriter可以拥有并处置FileStream但我更喜欢明确。

另外,您可能希望确保一次只执行一次此操作。 围绕整个对象的简单lock(_myMutex) {}就足够了。 _myMutexprivate static readonly _myMutex = new object();

另一个注意事项:您要确保文件可写。 应用程序通常被安装到Program Files不允许的文件写入(无UAC /系统)。

最后,如果您打开了该文件的其他程序(例如记事本),它将锁定该文件。 在这方面,有些编辑优于其他编辑。 因此,请确保关闭所有打开该文件的程序。

编辑:添加了完整示例。

EDIT2:更改了文件路径,请确保关闭编辑器。

private static readonly _fileMutex = new object();

public void SaveAll(int volume, int duration, string playing, int 
                        LBPindex, int LBSindex, string URL, int maximum)
{
    lock (_fileMutex) 
    {
        var filePath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "SaveDATA.bin");
        using (FileStream fs = new FileStream(filePath, FileMode.Create))
        {
            using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
            {
                sw.WriteLine("SETTINGS" + "|" + volume + "|" + duration + "|" + playing + "|" + LBPindex + "|" + LBSindex + "|" + URL + "|" + maximum);

                foreach (var item1 in Playlist.SavedPlaylists)
                {
                    sw.Write("PLAYLIST" + "|" + item1.Name + "|");
                    foreach (var item2 in item1.SavedSongs)
                    {
                        sw.WriteLine(item2.Path + "|" + item2.Title + "|" + item2.Author + "|" + item2.Album + "|" + item2.Release + "|" + item2.Genre + "|" + item2.Comment);
                    }
                }
                sw.Close();
            }
            fs.Close();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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