【问题标题】:Why am I getting IOexception after creating a file and trying to write in it?为什么在创建文件并尝试写入文件后出现 IOexception?
【发布时间】:2013-12-27 02:45:26
【问题描述】:

我只是初学者,所以不要苛刻。 尝试写入新创建的文件后出现 IOexception。

进程无法访问文件 'C:\Users\Ivan\Desktop\Compilerv4liteXP\fcc\bin\Debug.default',因为它正被另一个进程使用。

所以在方法文件开始时创建(检查,它就在那里),但程序结束(准确地说是返回 false)在 catch 阶段出现给定的异常。

方法:

private static bool setDefaultValues()
    {
        if(!createFile(defaultValuesPath))
            return false;
        File.Exists(defaultValuesPath);
        DefaultValues dv = new DefaultValues(cygwinPath, userPath,bashPath,outputPath,outputGlobalPath,cygwinDownloadSite);
        System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(DefaultValues));
        try
        {
            using (StreamWriter file = new StreamWriter(defaultValuesPath))
            {
                writer.Serialize(file, dv);
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

创建文件:

    private static bool createFile(string s)
    {
        if (!File.Exists(s))
        {
            try
            {
                File.Create(s);
            }
            catch (Exception e)
            {
                return false;
            }
        }
        return true;
    }

为什么会发生以及如何修复它(通过修复我正在考虑尝试创建一个新文件,如果它成功(或文件已经存在)然后写入它。

【问题讨论】:

标签: c# visual-studio-2010 serialization file-io ioexception


【解决方案1】:

File.Create() 返回一个锁定文件的FileStream
你需要Close()它。

更好的是,完全摆脱该功能并 File.Open(path, FileMode.Create)

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 2015-08-09
    相关资源
    最近更新 更多