我建立一個應該做到以下幾點應用程序:無法覆蓋包裹在一個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'中。 –