Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

c# - The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted

I am doing Image uploader in Asp.net and I am giving following code under my controls:

    string st;
    st = tt.PostedFile.FileName;
    Int32 a;
    a = st.LastIndexOf("");
    string fn;
    fn = st.Substring(a + 1);
    string fp;
    fp = Server.MapPath(" ");
    fp = fp + "";
    fp = fp + fn;
    tt.PostedFile.SaveAs("fp");

But during uploading or saving image the error message comes that The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted. So Please help me what is the problem

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I suspect the problem is that you're using the string "fp" instead of the variable fp. Here's the fixed code, also made (IMO) more readable:

string filename = tt.PostedFile.FileName;
int lastSlash = filename.LastIndexOf("");
string trailingPath = filename.Substring(lastSlash + 1);
string fullPath = Server.MapPath(" ") + "" + trailingPath;
tt.PostedFile.SaveAs(fullPath);

You should also consider changing the penultimate line to:

string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);

You might also want to consider what would happen if the posted file used / instead of in the filename... such as if it's being posted from Linux. In fact, you could change the whole of the first three lines to:

string trailingPath = Path.GetFileName(tt.PostedFile.FileName));

Combining these, we'd get:

string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
tt.PostedFile.SaveAs(fullPath);

Much cleaner, IMO :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...