error in my code when delete file? [duplicate] - c#

This question already has answers here:
IOException: The process cannot access the file 'file path' because it is being used by another process
(12 answers)
Closed 7 years ago.
I edit pic file in path and create new image file for there.my code is:
string[] files = Directory.GetFiles(string.Concat(Server.MapPath("/"), "tmp/"));
foreach (string path in files)
{
string filename = Path.GetFileName(path);
using (Bitmap b = new Bitmap(string.Concat(Server.MapPath("/"), "tmp/", filename)))
{
SolidBrush pixelBrush = new SolidBrush(Color.White);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(Brushes.White, 0, 0, 105, 40);
string outputFileName = string.Concat(Server.MapPath("/"), "tmp\\E", filename);
MemoryStream memory = new MemoryStream();
FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite);
b.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
fs.Close();
memory.Close();
b.Dispose();
}
File.Delete(path);
}
when delete old file error happend is:
Additional information: The process cannot access the file
'G:\project\WebApplication1\WebApplication1\tmp\b381ae6.jpg' because
it is being used by another process.
how to fix it?

Wrapping Graphics with using will fix it. You should dispose it also.
using (Bitmap b = new Bitmap(filePath))
{
using (Graphics g = Graphics.FromImage(b))
{
...
}
}
Also you can use using statements by combining them.
foreach (var path in files)
{
var filename = Path.GetFileName(path);
var filePath = string.Concat(tmpPath, filename);
using (var b = new Bitmap(filePath))
using (var g = Graphics.FromImage(b))
{
g.FillRectangle(Brushes.White, 0, 0, 105, 40);
var outputFileName = string.Concat(newPath, filename);
using (var memory = new MemoryStream())
using (var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
b.Save(memory, ImageFormat.Jpeg);
var bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
File.Delete(path);
}

write code in using scope and check File exists
Example
using (var b = new Bitmap(filePath))
using (var g = Graphics.FromImage(b))
using (var memory = new MemoryStream())
using (var fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
bool exists = File.Exists("Path");
if(exists)
{
// Code Here
}

You need to close the filestream before doing other operations on that file ;)

Related

Invalid zip file reading from a Stream in C#

I have the following code:
private static byte[] ConverterStringToByte(Stream body)
{
string fileName = "data_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
// Take out the bytes from the memory stream and safely close the stream
using (var ms = new MemoryStream())
{
body.CopyTo(ms);
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false))
{
var zipEntry = zipArchive.CreateEntry(fileName, CompressionLevel.Optimal);
using (BinaryWriter writer = new BinaryWriter(zipEntry.Open()))
{
ms.Position = 0;
writer.Write(ms.ToArray());
}
}
return ms.ToArray();
}
}
I am downloading the file successfully, however I'm getting
invalid file
when trying to open
I think it should be something like this. Not sure about fileName though, because it's the name of the file being put into archive, so I don't think it should have *.zip extension. Unless you are creating a zip of zips.
static byte[] ConverterStringToByte(Stream body)
{
string fileName = #"data_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";
using (var ms = new MemoryStream())
{
using (var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false))
{
var zipEntry = zipArchive.CreateEntry(fileName, CompressionLevel.Optimal);
using (var destStream = zipEntry.Open())
{
body.CopyTo(destStream);
}
}
return ms.ToArray();
}
}

Invalid C# Zip File After Compressing

I am writing a code to compress a ZIP file in C# using the built in .NET library:
using System.IO.Compression;
using System.IO;
But, however, when the compression finishes, the code outputs an invalid zip file. It seems like somewhere down the line in the code, the file either did not write properly or close fully. I have used dispose and close to release the resources.
public bool CompressFile(FileInfo theFile)
{
StringBuilder compressSuccess = new StringBuilder();
FileStream sourceFile = File.OpenRead(theFile.FullName.ToString());
FileStream destinationFile = File.Create(theFile.FullName + ".zip");
byte[] buffer = new byte[sourceFile.Length];
sourceFile.Read(buffer, 0, buffer.Length);
using (GZipStream output = new GZipStream(destinationFile,
CompressionMode.Compress, true))
{
output.Write(buffer, 0, buffer.Length);
}
sourceFile.Dispose();
destinationFile.Dispose();
sourceFile.Close();
destinationFile.Close();
return true;
}
What would I been doing wrong? Is it because I am forcing an extension ".zip"?
Following the link suggested by FrankJames, this is an example of code to create a zip file:
var zipFile = #"e:\temp\outputFile.zip";
var theFile = #"e:\temp\sourceFile.txt";
using (var zipToCreate = new FileStream(zipFile, FileMode.Create))
{
using (var archive = new ZipArchive(zipToCreate, ZipArchiveMode.Create))
{
var fileEntry = archive.CreateEntry("FileNameInsideTheZip.txt");
using (var sourceStream = File.OpenRead(theFile))
using (var destStream = fileEntry.Open())
{
var buffer = new byte[sourceStream.Length];
sourceStream.Read(buffer, 0, buffer.Length);
destStream.Write(buffer, 0, buffer.Length);
destStream.Flush();
}
}
}
I see you never used the Flush method that force to write to the stream.
I rewrite your code using a better style (using instead of the dispose).
Try it and let us know:
public bool CompressFile(FileInfo theFile)
{
using (var sourceStream = File.OpenRead(theFile.FullName))
using (var destStream = File.Create(theFile.FullName + ".zip"))
{
var buffer = new byte[sourceStream.Length];
sourceStream.Read(buffer, 0, buffer.Length);
using (var zipStream = new GZipStream(destStream, CompressionMode.Compress, true))
{
zipStream.Write(buffer, 0, buffer.Length);
zipStream.Flush();
}
destStream.Flush();
}
return true;
}

Sevenzipsharp CompressStream throws Exception: Value cannot be null

I am trying out following code in order to compress and save a bitmap of a screenshot but get this error. I haven't tried using CompressFiles as I have to do it using memory stream.
public void CompressAndSaveBitmap(Bitmap bitmap)
{
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream file = new FileStream("XYZ", FileMode.Create, System.IO.FileAccess.Write))
{
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
// tried these but they don't work.
//memStream.Seek(0, 0);
//memStream.Position = 0;
this.compressor.CompressStream(memStream, file); // throws error here
// also tried the following to see if Bitmap contains the problem
//UnicodeEncoding uniEncoding = new UnicodeEncoding();
//byte[] firstString = uniEncoding.GetBytes("Invalid file path characters are: ");
//int count = 0;
//while (count < firstString.Length)
//memStream.WriteByte(firstString[count++]);
//memStream.Flush();
////memStream.Seek(0, 0);
//memStream.Position = 0;
//this.compressor.CompressStream(memStream, file);
}
}
}
Compressor initialization code:
public Compressor()
{
SevenZipCompressor.SetLibraryPath(#"D:\7z.dll");
this.compressor = new SevenZip.SevenZipCompressor();
compressor.CompressionLevel = CompressionLevel.Ultra;
compressor.CompressionMethod = CompressionMethod.Ppmd;
}
It's crashes on this line in the library:
var lockObject = (object) _files ?? _streams;
lock (lockObject) // here in ArchiveUpdateCallback.cs
I see that the file is created but it's corrupt.
I was able to successfully compress file using following code:
public void CompressAndSaveBitmap(Bitmap bitmap)
{
using (MemoryStream memStream = new MemoryStream())
{
using (FileStream file = new FileStream("XYZ", FileMode.Create, System.IO.FileAccess.Write))
{
bitmap.Save(memStream, System.Drawing.Imaging.ImageFormat.Bmp);
// tried these but they don't work.
//memStream.Seek(0, 0);
//memStream.Position = 0;
SevenZipCompressor compressor =
new SevenZipCompressor
{
CompressionLevel = CompressionLevel.Ultra,
CompressionMethod = CompressionMethod.Lzma
};
compressor.CompressStream(memStream, file); // throws error here
}
}
}
Following was the bitmap file:
Executed code:
Bitmap bmp = new Bitmap("Test.bmp");
res.CompressAndSaveBitmap(bmp);
After execution got following output:
Opened the file with WinRar and extracted file:
In folder found the extracted image:
UPDATE:
I think the only problem with OP's code is this.compressor is not initialized.

File is being used by another process on generating thumbnail

I'm working on file manager project. I need to generate thumbnail if file is of image type. i'm able to get by using IHttpHandler with method
Sytem.Drawing.Image.GetThumbnailImage(),
Here is some code
Hashtable ht;
ht = new Hashtable();
using (FileStream fInfo = new FileStream(context.Server.MapPath(url), FileMode.Open))
{
byte[] bFile;
bFile = GenerateThumbnail(fInfo, XLen, YLen);
ht.Add(id, bFile);
fInfo.Close();
Byte[] arrImg = (byte[])ht[id];
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(arrImg);
context.Response.End();
}
private byte[] GenerateThumbnail(Stream fStream, string xLen, string yLen)
{
using (Image img = Image.FromStream(fStream))
{
Image thumbnailImage = img.GetThumbnailImage(int.Parse(xLen), int.Parse(yLen), new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
using (MemoryStream imageStream = new MemoryStream())
{
thumbnailImage.Save(imageStream,System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageContent = new Byte[imageStream.Length];
imageStream.Position = 0;
imageStream.Read(imageContent, 0, (int)imageStream.Length);
return imageContent;
}
}
}
Problem
Newly uploaded file on genrating thumb throwing expection : being used by another process, after sometime its shows the thumbnail. Q. where im missing to close the stream ?

How to save MP3 file from the internet on Windows Phone 7?

I'm trying to download and save an .mp3 file from the internet, but got stuck with stream from the external link:
private void saveSound()
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = new IsolatedStorageFileStream("123.mp3", FileMode.Create, iso))
{
//Here should be this Stream from the Internet...
//Uri: "http://my-site.com/mega-popular-song.mp3"
StreamResourceInfo rs = new StreamResourceInfo(stream, "audio/mpeg");
int count = 0;
byte[] buffer = new byte[4096];
while (0 < (count = rs.Stream.Read(buffer, 0, buffer.Length)))
{
fs.Write(buffer, 0, count);
}
fs.Close();
}
}
What should this stream look like? What is the best way to download and save .mp3 files?
I'm sure this article gets you there. Like Bob mentioned, you'll have to use a WebClient. Basically this is the code that does the magic:
wc.OpenReadCompleted += ((s, args) =>
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
store.DeleteFile(fileName);
using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
byte[] bytesInStream = new byte[args.Result.Length];
args.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);
fs.Write(bytesInStream, 0, bytesInStream.Length);
fs.Flush();
}
}
});
But I would read the complete article to fully understand what happens. Hope this helps!

Categories