문제

I am just beginner so don't be harsh. I am getting IOexception after trying to write to newly created file.

The process cannot access the file 'C:\Users\Ivan\Desktop\Compilerv4liteXP\fcc\bin\Debug.default' because it is being used by another process.

So at the start of the method file is created (checked, it was there), but program ends (it returns false to be precise) in catch phase with given exception.

Method:

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

createFile:

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

Why is it happening and how can it be fixed (and by fixed I am thinking about trying to create a new file and if it succeeded (or file already exists) then write to it.

도움이 되었습니까?

해결책

File.Create() returns a FileStream that locks the file.
You need to Close() it.

Better yet, get rid of that function entirely and File.Open(path, FileMode.Create).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top