On Thursday, 9 May 2019 at 10:09:23 UTC, Cym13 wrote:
Hi,

this is likely not related to D itself but hopefully someone can help me with this since I'm rather new to windows programming, I mainly work on linux. I'm trying to bundle a DLL in a binary, write it in a temp folder, use it and remove the dangling file.

So far I have the following file:

    import std;

    void main(string[] args) {
        import core.runtime;
        static immutable libcurl = import("libcurl.dll");

        import std.file: write;
        auto libpath = tempDir.buildPath("libcurl.dll");
        libpath.write(libcurl);

        auto libcurlMem = rt_loadLibrary(libpath.toStringz);

        import std.net.curl;
        "https://dlang.org/".byLine.count.writeln;

        rt_unloadLibrary(libcurlMem);
        remove(libpath);
    }

Compiled with:  dmd.exe -Jlibdir test.d

It almost work, I can write, load and use the library, but when it comes to
removing it nothing works.

std.file.FileException@std\file.d(1045): C:\users\cym13\Temp\libcurl.dll: Access denied.
----------------
0x00402377 in EntryPoint
0x00413BC7 in EntryPoint
0x00413B49 in EntryPoint
0x004139E3 in EntryPoint
0x0040B77F in EntryPoint
0x7B4754C2 in call_process_entry
0x7B477FC6 in ExitProcess
0x7B4754CE in call_process_entry

I tried using an explicit File handle to explicitely close the file after
writing to it but that doesn't change anything.

I'm pretty sure I'm missing something basic about the way windows handles open files but I don't know what, could someone explain why this doesn't work
the way I expect it to?

Well, I've had similar issue. The error message says "access denied" which I believe refers to the tmp directory; i.e, the user that is running your executable has no permissions to delete that file. To be honest, I find all the permissions issues on Windows a pain the pass so I did a simple tmp files manager. My application create a tmp folder in same folder as in the executable's directory then delete it when the application finishs. I also did write my own function to geneate a random string meant to be used as tmp filename.

To delete the file, it might be finishing something and the OS may hold it for some while; so try to delete the file a couple of times, with some interval between the attemps, I do something like this:

void deleteFile(string filename)
{
        import std.file : remove, FileException;

        enum int nAttempts = 5;
        enum int interval = 200; // value in ms

        int n = nAttempts;
        do
        {
                try
                {
                        remove(filename);
                }
                catch(FileException)
                {
// the file may be temporary busy or something, so we try again after a while, few times.
                        sleep(interval);
                }
        } while(n --> 0);
}

Reply via email to