将所有图像从文件夹插入数据库,而不指定图像名称或类型

时间:2014-07-16 04:58:48

标签: c# sql-server

我需要遍历一个文件夹并获取所有图像并将其加载到SQL Server database;原样;意味着图像的格式。

在我的代码中,我必须指定图像名称,这是一个问题,特别是因为我事先不知道图像的名称。我还尝试通过forloop循环遍历目录,但这不起作用。

以下是完整的代码:

class Program
{

    string imageFileLocation = @"C:\dev\dbimage\";
    string imageFilePrefix = "test";
    string imageFileType = ".png";
    int numberImageFiles = 1;
    int maxImageSize = 10000;
    SqlConnection conn = null;
    SqlCommand cmd = null;

    private void LoadImages()
    {

        try
        {
            conn = new SqlConnection(@"MyConnectionStuff");
            conn.Open();
            cmd = new SqlCommand();
            cmd.Connection = conn;

            PrepareInsertImages();

            for (int i = 1; i <= numberImageFiles; i++)
            {
                ExecuteInsertImages(i);
            }
        }
        catch (SqlException ex)
        {
            Console.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }

    private void ExecuteCommand(string cmdText)
    {
        int cmdResult;
        cmd.CommandText = cmdText;
        cmdResult = cmd.ExecuteNonQuery();
    }

    private void PrepareInsertImages()
    {
        cmd.CommandText = @"insert into ImageTable 
values (@ImageFile, @ImageData)";
        cmd.Parameters.Add("@imagefile", SqlDbType.NVarChar, 20);
        cmd.Parameters.Add("@imagedata", SqlDbType.Image, 1000000);
        cmd.Prepare();
    }

    private void ExecuteInsertImages(int imageFileNumber)
    {
        string imageFileName = null;
        byte[] imageImageData = null;
        imageFileName = imageFilePrefix + imageFileNumber.ToString() 
+ imageFileType;
        imageImageData = LoadImageFile(imageFileName, imageFileLocation, 
maxImageSize);
        cmd.Parameters["@ImageFile"].Value = imageFileName;
        cmd.Parameters["@ImageData"].Value = imageImageData;
        ExecuteCommand(cmd.CommandText);
    }

    private byte[] LoadImageFile(string fileName, string fileLocation, 
int maxImageSize)
    {
        byte[] imagebytes = null;
        string fullpath = fileLocation + fileName;
        FileStream fs = new FileStream(fullpath, FileMode.Open, 
FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imagebytes = br.ReadBytes(maxImageSize);
        return imagebytes;
    }


    static void Main(string[] args)
    {
        Program program = new Program();
        program.LoadImages();
        Console.ReadKey();
    }

}

1 个答案:

答案 0 :(得分:2)

您可以在以下文件夹中枚举.png文件:

foreach(string filePath in Directory.EnumerateFiles(@"C:\dev\dbimage", "*.png"))
{

}

filePath将包含文件的完整路径。如果您只想获取没有完整路径的文件名,请执行以下操作:

string fileName = Path.GetFileName(filePath);

DirectoryPath都在 System.IO 命名空间中。