开发者

C# How can I read all jpeg files in a directory using a Filestream so the files aren't locked?

开发者 https://www.devze.com 2023-02-03 05:30 出处:网络
How can I read all jpeg files in a directory using a Filestream so the files aren\'t locked? My current code is below, there is no mention of Filestream as I can\'t get it to work. Many thanks for any

How can I read all jpeg files in a directory using a Filestream so the files aren't locked? My current code is below, there is no mention of Filestream as I can't get it to work. Many thanks for any help.

    public Form1()
    {
        InitializeComponent();

        images = new List<Image>();
        // ad开发者_Go百科d images

        DirectoryInfo di = new DirectoryInfo(@"\\server\files\");
        FileInfo[] finfos = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
        foreach (FileInfo fi in finfos)
            images.Add(Image.FromFile(fi.FullName));

   }

    private void buttonNext_Click(object sender, EventArgs e)
    {
        index++;
        if (index < 0 || index >= images.Count)
            index = 0;
        pictureBox1.Image = images[index];
        int count = index + 1;
        labelCount.Text = "Showing " + count.ToString() + " of " + images.Count;
    }


You need to call Open and pass FileShare.ReadWrite:

using (var stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    images.Add(Image.FromStream(stream));


It is the Image.FromFile method which locks the file. As an alternative you could try to read the contents of the file into a buffered memory stream and then load the image from this stream using Image.FromStream.

0

精彩评论

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