开发者

how to open file if it exists otherwise redirect to a page

开发者 https://www.devze.com 2023-02-22 08:31 出处:网络
iam trying to tell the page to open a certain aspx if it exists otherwise it should redirect to another page here the code iam using:

iam trying to tell the page to open a certain aspx if it exists otherwise it should redirect to another page here the code iam using:

   protected void Page_Load(object sender, EventArgs e)
{
    string str = "~/User" + "/" + Page.开发者_如何学JAVAUser.Identity.Name + "/" + Page.User.Identity.Name + ".aspx";
    FileInfo fi = new FileInfo(str);
    if (fi.Exists) {
        Response.Redirect(str);
    }
    else {
    Response.Redirect("Page.aspx");
        }
}

but i will always redirect to the page.aspx even if the original page exists

thanks


You need to pass the full path to FileInfo. Use Server.MapPath to map from your virtual path to a full path, like this:

string str = "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".aspx";
string path = Server.MapPath(str);
if (File.Exists(path)) 
{
    Response.Redirect(str);
}
else
{
    Response.Redirect("Page.aspx");
}


I'm guessing it is because you are using ~. ~ is used for resolving the web URL base path. Not the windows base path.

Instead of

string str = "~/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".aspx";

try

string str = Server.MapPath("/User" + "/" + Page.User.Identity.Name + "/" + Page.User.Identity.Name + ".aspx"")


I'd be careful with the ~ path alias. I'd try using an absolute path instead of the alias and see if that helps. If it's always redirecting to Page.aspx then the file you think you're looking at doesn't exist.


Drop the ~

string str = string.Format("/User/{0}/{0}.aspx",Page.User.Identity.Name);
string path = Server.MapPath(str) 
0

精彩评论

暂无评论...
验证码 换一张
取 消