christopher achard
christopher achard

Reputation: 73

File.Exists() file not found after impersonate

Firstable, I am in WebForms ASP.NET.

In a method I wrote,

        string source = Global.PathTempFile + fileNamePosted + ".htm";
        using (FileStream fs = new FileStream(source, FileMode.Create))
        {
            using(StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
            {
                w.WriteLine(Request.Form["hide_redige"]);
            }
        }
        bool exist = File.Exists(source); // true here (for test)

        new MoveFile(source, Global.HADmdcdc + "\\" + fileNamePosted + ".htm", true);

This code create a new file in my temporary folder, at this moment, the file is recognized by File.Exists()

But, for security reason, I created a class to manipulate the file as a particular User (which has rights to write in target folder)

    public MoveFile(string sourcePath, string targetPath, bool isImpersonate)
    {
        if (isImpersonate)
            moveImp(sourcePath, targetPath);
        else
            move(sourcePath, targetPath);
    }
    private void moveImp(string sourcePath, string targetPath)
    {
        if (imp.impersonateValidUser(id["domain"], id["login"], id["password"]))
            move(sourcePath, targetPath);

        imp.undoImpersonation();
    }
    private void move(string sourcePath, string targetPath)
    {
        if (File.Exists(sourcePath)) // false here
        {
            if (File.Exists(targetPath))
                File.Delete(targetPath);

            File.Move(sourcePath, targetPath);
        }
    }

So, my question is, why the test of File.Exists() return a different value? Also, i'm sure that the file exists.

Upvotes: 1

Views: 543

Answers (1)

Boris Evraev
Boris Evraev

Reputation: 82

If the file exists this sounds like permission issue.

You need to check permissions of your Application pool

To find your Application pool name :

enter image description here

enter image description here

Now when you found your Application pool open it :

enter image description here

Chenge it's itentity:

enter image description here enter image description here

Choose custom account :

enter image description here

Set a user that can access to your file's directory

Upvotes: 0

Related Questions