2012-05-14 105 views
2

我试图通过使用c#将图像添加到目录中。我将使用这个图像在gridview中显示。我编写了代码,但出现错误,无法解决。我有一个名为images的directoy。这是我得到错误FileUpload1.SaveAs(Server.MapPath(“images /”+ FileName)。它说C:\ Users \ user \ Documents \ Visual Studio 2008 \ WebSites \ WebSite1 \ images \ im1.jpg'部分。路径找不到的下面是我的代码:将图像保存到目录c#

string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 
FileUpload1.SaveAs(Server.MapPath("images/" + FileName)); 
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 
SqlConnection con = new SqlConnection(strConnString); 
string strQuery = "INSERT INTO Books (Book_Name,Author_Name,FileName, FilePath, In_Lib) VALUES (@BN,@AN,@FileName, @FilePath,@LIB)"; 
SqlCommand cmd = new SqlCommand(strQuery); 
cmd.Parameters.AddWithValue("@BN", TextBox1.Text); 
cmd.Parameters.AddWithValue("@AN", TextBox2.Text); 
cmd.Parameters.AddWithValue("@FileName", FileName); 
cmd.Parameters.AddWithValue("@FilePath", "images/" + FileName); 
cmd.Parameters.AddWithValue("@LIB", "YES"); 
cmd.CommandType = CommandType.Text; 
cmd.Connection = con; 
+0

请注意,当您将此上传到服务器时,您可能必须为您的应用授予写入您要保存到的文件夹的权限。 – peroija

回答

2

您试图保存到一个不存在的目录

您需要创建的目录层次结构,然后才能保存它

+0

是的,你是对的。我在我的网站内创建了文件夹,现在它工作得很好 –

0

使用FileUpload1.SaveAs(Server.MapPath("/") + "\\images\\" + FileName);

示例代码

Server.MapPath(".") returns D:\WebApps\shop\products 
Server.MapPath("..") returns D:\WebApps\shop 
Server.MapPath("~") returns D:\WebApps\shop 
Server.MapPath("/") returns C:\Inetpub\wwwroot 
Server.MapPath("/shop") returns D:\WebApps\shop 
0

也许你的问题在你的道路上。

检查您的网站中是否有文件夹名称images

如果尝试像Server.MapPath("~/images/"+FileName);

也有一个看看这篇文章约ASP.NET Web Project Paths

0
string cntPath = System.IO.Directory.GetCurrentDirectory(); 
FileUpload1.SaveAs(cntPath + "\\images\\" + FileName); 

我做这在我的C#应用​​程序之一,它工作正常的。

相关问题