В приложении на С# работаю с файлом на USB-flash c помощью потоков FileStream (открываю файл, пишу, закрываю). После этого не удается безопасно извлечь USB-flash. После закрытия приложения USB-flash безопасно извлекается. Как безопасно извлечь USB-flash до закрытия приложения (это важно!!!)?
Код
FileStream str_usb = null;
string sPath = "K:\\";
string name = "qwe.txt";
str_usb = new FileStream(sPath + name, FileMode.Create);
int size = 1000;
byte[] buffer;
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
for (int y = 0; y < 1048576; y++)
buffer [y] = (byte)rnd.Next(0, 255);
str_usb.Write(buffer, 0, buffer.Length);
}
str_usb.Close();
str_usb.Dispose();
Добавляю код, который коммпилируется
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace WindowsFormsApplication1
{
class Class1
{
public static void write_usb()
{
FileStream str_usb = null;
string sPath = "K:\\";
string name = "qwe.txt";
str_usb = new FileStream (sPath + name, FileMode.Create);
int size = 1000;
byte[] buffer = new byte[1048576];
Random rnd = new Random();
for (int i = 0; i < size; i++)
{
for (int y = 0; y < 1048576; y++)
buffer [y] = (byte)rnd.Next(0, 255);
str_usb.Write(buffer, 0, buffer.Length);
}
str_usb.Close();
str_usb.Dispose();
}
}
}
Dispose() / using
?Dispose
. Поэтому остаются занятыми неуправляемые ресурсы ниже уровняFileStream
. Оберните весь ваш код в операторыusing
.