C# 当路径为空时,如何将默认图像插入数据库?
我面临一个问题,当我想将图像插入数据库,但路径为空时,我希望将默认图片插入默认图片。这可能吗C# 当路径为空时,如何将默认图像插入数据库?,c#,sql,wpf,visual-studio-2010,C#,Sql,Wpf,Visual Studio 2010,我面临一个问题,当我想将图像插入数据库,但路径为空时,我希望将默认图片插入默认图片。这可能吗 if (imageName != "") { MessageBox.Show(imageName); //Initialize a file stream to read the image file FileStream fs = new FileS
if (imageName != "")
{
MessageBox.Show(imageName);
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();
cmdInsert.Parameters.AddWithValue("@fImage", imgByteArr);
}
else {
imageName = @"/HouseWivesSavior;component/images/unknown.jpg";
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();
cmdInsert.Parameters.AddWithValue("@fImage", imgByteArr);
cmdInsert.Parameters.AddWithValue("@fImage", "");
}
与其检查空字符串,不如检查null
var imagePath = string.Empty;
if (imageName == null)
imagePath = "pathToDefaultImage";
else
imagePath = "pathToNonDefaultImage"
... do your work here using imagePath as the path
但您可以在数据库中保存null。然后,当您从数据库加载图像时,只要在遇到null时设置一个默认图像。这样,您就不会反复保存同一个默认图像。不要这样做。为什么要在数据库中保留默认图像?这在存储和网络流量方面非常昂贵。假设有1024条记录具有相同的默认映像200KB,您将浪费200MB的db存储空间。不仅如此,从数据库检索blob是一项非常昂贵的操作 避免它,如果路径为空,则插入一个空值。然后,让您的业务逻辑决定在没有图像的情况下该做什么 顺便说一下,不要像你在问题中那样检查空字符串。改为使用string对象的IsNullOrEmpty静态方法
if(!string.IsNullOrEmpty(imageName))
这将更有效地计算空值和空值
希望能有帮助
Leo为什么还要在数据库中插入默认图像?它需要大量的空间,而且,相同的BLOB文件会重复很多行。如果您使用的是Oracle,您可以使用重复数据消除来避免这种情况,但存储默认映像而不是空映像仍然是一个非常糟糕的主意。我们当然可以在运行时用前端的图像替换这个空值。谢谢你,伙计。。。我用这段代码计算出来:因为我在数据库中的数据类型是Varbinary(MAX):if(!string.IsNullOrEmpty(imageName)){//Insert image into database}else{//else inser null into database cmdInsert.Parameters.Add(@fImage),SqlDbType.VarBinary,-1);cmdInsert.Parameters[“@fImage”].Value=DBNull.Value;}谢谢你。。。我用这段代码计算出来:因为我在数据库中的数据类型是Varbinary(MAX):if(!string.IsNullOrEmpty(imageName)){//Insert image into database}else{//else inser null into database cmdInsert.Parameters.Add(@fImage),SqlDbType.VarBinary,-1);cmdInsert.Parameters[“@fImage”].Value=DBNull.Value;}