我建立一个应该做到以下几点应用程序:无法覆盖包裹在一个using语句文件
- 用户选择ListBox中的一个元素(例如:青蛙)
- 与该元素对应的图片作为背景打开为用户可以在其上绘制的背景
- 当用户选择列表框的另一个元素时,画布将保存为以非选中元素命名的图片,其中“新增“(示例:frogNew)
- 这个新元素添加到列表框中,如果用户再次编辑它,它下保存的同名(例如:frogNew)
事情工作了,除了部分我试图用相同的名字保存一个画布(frogNew)。我收到一个错误,说我无法保存文件,因为它已经打开。你能告诉我,如果不在我的代码中正确关闭文件?
private void save_picture(string name)
{
//This part takes a screenshot of the canvas, named "paintSurface"
RenderTargetBitmap rtb = new RenderTargetBitmap((int)paintSurface.RenderSize.Width, (int)paintSurface.RenderSize.Height, 96d, 96d, System.Windows.Media.PixelFormats.Default);
rtb.Render(paintSurface);
BitmapEncoder pngEncoder = new PngBitmapEncoder();
pngEncoder.Frames.Add(BitmapFrame.Create(rtb));
//If the file already exists, we add "New" to its name
var regex1 = new Regex(@"New$");
if (regex1.Match(nom).ToString() == "")
{
using (var fs = System.IO.File.OpenWrite(@"D:\Test" + name + "New.png"))
{
pngEncoder.Save(fs);
}
}
else
{
using (var fs = System.IO.File.OpenWrite(@"D:\Test" + name + ".png"))
{
pngEncoder.Save(fs);
}
}
}
private void listBox1_SelectedIndexChanged(object sender, SelectionChangedEventArgs e)
{
//When the index of listbox changes, I save the canvas in a file named after the former index
List<string> oldItemNames = new List<string>();
if (e.RemovedItems.Count != 0)
{
var oldPhoto = e.RemovedItems[0].ToString();
save_picture(oldPicture);
}
//I start a new canvas with the picture corresponding to the new index as a background
paintSurface.Children.Clear();
ImageBrush newBrush = new ImageBrush();
newBrush.ImageSource = new BitmapImage(new Uri(@"D:\Test" + listBox1.SelectedItem.ToString() + ".png", UriKind.Relative));
paintSurface.Background = newBrush;
}
任何想法,为什么这条线“using (var fs = System.IO.File.OpenWrite(@"D:\Test" + name + ".png"))"
总是给我,这个文件已经打开错误?我怎么能收呢?
问题可能是你的'BitmapEncoder'('pngEncoder'),你试过关闭/处理那个对象吗? –
不,我没有。你介意告诉我如何正确地做到这一点? –
@LoukoumMira'Dispose()'或者包装在'using'中。 –