Search code examples
c#filetaskini

Write temp file and move to .ini file via interface causes Error in C#


I have a method which prepares all the necessary data for me and then I work with an interface:

myFileCreator.Create(myData.ToString(), PathToWriteMyFile, SomeMoreDataAsAList);

My Interface:

public interface IMyIniFileCreator
{
    void Create(string dataName, string dataPath, List<SomeModes> modeList);

    void Delete(string dataName, string dataPath);
}

It should be noted here that the Create and Delete methods were previously a Task

So

public interface IMyIniFileCreator
{
    Task Create(string dataName, string dataPath, List<SomeModes> modeList);

    Task Delete(string dataName, string dataPath);
}

The Create() looks like the following and should work fine here:

public class MyIniFileCreator : ComponentBase,
                                IMyIniFileCreator
{
    public void Create(string dataName, string dataPath, List<SomeModes> modeList)
    {
        var pathToMode = Path.Combine(appDataPath, modeName + ".ini");
        var tempFile = Path.ChangeExtension(pathToMode, "tmp");

        var listOfSection = new List<IniSection>();
        
        // some more code with list of sections etc.
        
        var modeFileInfo = new IniDocument();
        modeFileInfo.AddRange(listOfSection);

        Check.State(tempFile.IsNotNullOrEmpty(), "modes.ini does not exist");

        File.WriteAllText(tempFile, SimpleIniParser.WriteSections(modeFileInfo), Encoding.Default);
        // This is needed when something changes in the file. 
        // Here the old ini must be deleted and the new one written. 
        // Unfortunately we do not have a `ForceMove` available.
        FileSystemHelper.DeleteFileIfExisting(pathToMode);
        FileSystemHelper.MoveDirectory(tempFile, pathToMode);
    }
}

The code also runs through and my modeName.ini file also exists and has been fully and correctly described. However the error is thrown that

Unable to create directory 'C:\...\data\...\123456789abc.ini'

This in turn has the consequence that it goes no further in my main class (line 1). What can be the reason for this, that it still worked with the Task in the interface (here a Task.CompletedTask was returned) and it doesn't work with the void anymore and this strange error message appears, although it runs through and the .ini file exists.


Solution

  • You are calling to MoveDirectory which is for moving directories.

    Instead you should call File.Move() which is for moving files.