C# How can I read all jpeg files in a directory using a Filestream so the files aren't locked?
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.
精彩评论