Unkown Exceptions in following code - c#

I'm writing Windows 10 UWP that takes a picture of a user and then places that picture in another one. (It'll be more useful once I have the specific pictures). Basically, the program seems to be unable to access pictures in my computer no matter where they are stored. The following line:
input2 = new FileStream(file2.Path, FileMode.Open, FileAccess.Read);
also throws an exception, sometimes saying file2 is in use other times saying that I should place it in a task.run box.
Suggestions? I'm totally new to C#. Thank you!
private async void processing()
{
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(1, 1);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
StorageFile file2;
Image playbutton = new Image();
try
{
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
playbutton.Source = bmp;
stream = null;
}
catch (Exception ex)
{
return;
}
Image frame = new Image();
try
{
FileOpenPicker picker = new FileOpenPicker();
picker.ViewMode = PickerViewMode.Thumbnail;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".png");
file2 = await picker.PickSingleFileAsync();
file2 = await StorageFile.GetFileFromPathAsync("C:\\Users\\Kyle\\Downloads\\BingWallpaper-2016-02-07");
IRandomAccessStream stream = await file2.OpenAsync(FileAccessMode.ReadWrite);
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
playbutton.Source = bmp;
frame.Source = bmp;
stream = null;
}
catch (Exception ex)
{
return;
}
FileStream input2;
var t = Task.Run(() => {
input2 = new FileStream(file2.Path, FileMode.Open, FileAccess.Read);
byte[] arrayForImage2;
byte[] buffer2 = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input2.Read(buffer2, 0, buffer2.Length)) > 0)
{
ms.Write(buffer2, 0, read);
}
arrayForImage2 = ms.ToArray();
}
byte[] arrayForImage1;
FileStream input = new FileStream(file.Path, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
arrayForImage1 = ms.ToArray();
}
if (arrayForImage1.Length > arrayForImage2.Length)
{
for (int x = 0; x < arrayForImage2.Length; x++)
{
arrayForImage1[x] = arrayForImage2[x];
}
FileStream fSO = new FileStream("C:/Users/Kyle/Pictures/imageCompiled.png", FileMode.Create, FileAccess.Write);
fSO.Write(arrayForImage1, 0, arrayForImage1.Length);
}
else if (arrayForImage1.Length < arrayForImage2.Length)
{
for (int x = 0; x < arrayForImage1.Length; x++)
{
arrayForImage2[x] = arrayForImage1[x];
}
FileStream fSO = new FileStream("C:/Users/Kyle/Pictures/imageCompiled.png", FileMode.Create, FileAccess.Write);
fSO.Write(arrayForImage2, 0, arrayForImage2.Length);
}
});
t.Wait();
}
}
}

also throws an exception, sometimes saying file2 is in use
I see you are not closing the streams by calling close() or dispose() methods.
FileStream fSO = new FileStream("C:/Users/Kyle/Pictures/imageCompiled.png", FileMode.Create, FileAccess.Write);
fSO.Write(arrayForImage2, 0, arrayForImage2.Length);
Here, fSO.close(); should be called after work is done.
Also, input, input2 and other streams that you are using should be checked if they are closed properly.

Related

GZipStream sum compressing blocks to file

I make an archiver with block-by-block reading and file compression. I put the compressed block in FileStream.
I am reading the 5 mb block. The problem is that if I compress a pic of 8 mb, then when I pull it out of the resulting archive, its sum-hash does not match the original and it opens pic halfway, and the size is the same... I don’t know what to try. I ask for help.
Read chunk void:
private byte[] ReadChunk(int chunkId)
{
using (var inFile = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long filePosition = chunkId * chunkDataSize;
int bytesRead;
if (inFile.Length - filePosition <= chunkDataSize)
{
bytesRead = (int)(inFile.Length - filePosition);
}
else
{
bytesRead = chunkDataSize;
}
var lastBuffer = new byte[bytesRead];
inFile.Read(lastBuffer, 0, bytesRead);
return lastBuffer;
}
}
Compress and write void:
private void CompressBlock(byte[] bytesTo)
{
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gs = new GZipStream(ms, CompressionMode.Compress))
{
gs.Write(bytesTo, 0, bytesTo.Length);
}
byte[] compressedData = ms.ToArray();
using (var outFile = new FileStream(resultFile, FileMode.Append))
{
BitConverter.GetBytes(compressedData.Length).CopyTo(compressedData, 4);
outFile.Write(compressedData, 0, compressedData.Length);
}
}
}

Async download file in c#

I need help to improve this code but I do not understand where I made a mistake. The file is downloaded but in a corrupted format. I am using cookies also which is a required part of this method.
/*Downlod task */
public static async Task<int> CreateDownloadTask(string urlToDownload,string sDestinationPath, string cookiedstr)
{
int BufferSize = 4096;
int receivedBytes = 0;
int totalBytes = 0;
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.Cookie, cookiedstr);
using (var stream = await client.OpenReadTaskAsync(urlToDownload))
{
using (MemoryStream ms = new MemoryStream())
{
int read = 0;
totalBytes = Int32.Parse(client.ResponseHeaders[HttpResponseHeader.ContentLength]);
var buffer = new byte[BufferSize];
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
FileStream file = new FileStream(sDestinationPath, FileMode.Append, FileAccess.Write);
ms.Position = 0;
ms.WriteTo(file);
file.Flush();
file.Close();
buffer = new byte[BufferSize];
receivedBytes += read;
Console.WriteLine(receivedBytes + " " + totalBytes);
// DownloadBytesProgress args = new DownloadBytesProgress(urlToDownload, receivedBytes, totalBytes);
}
ms.Close();
}
return receivedBytes;
}
}

About Parallel.For and Lock

if (File.Exists(copypath)) File.Delete(copypath);
using (FileStream inputstream = new FileStream(plainpath, FileMode.Open))
{
using (FileStream outputstream = new FileStream(copypath, FileMode.CreateNew))
{
Object lock1 = new Object();
long inputlength = inputstream.Length;
Parallel.For((long)0, (long)(inputlength / bufferSize) + ((inputlength%bufferSize)>0?1:0), (i) =>
{
byte[] parallelbuff = new byte[bufferSize];
long cursor = -1;
lock (lock1)
{
cursor = (long)(i * bufferSize);
inputstream.Seek(cursor, SeekOrigin.Begin);
read = inputstream.Read(parallelbuff, 0, buff.Length);
}
if (read > 0)
{
lock (lock1)
{
outputstream.Seek(cursor, SeekOrigin.Begin);
outputstream.Write(parallelbuff, 0, read);
}
}
});
}
}
This is a piece of my .NET 4.5 C# code for copying file from 'plainpath' to 'copypath'.
But it doesn't copy some parts of the original file.
Can you tell me about my mistake in it?

Network Programming : receiving image file in dynamic Image Object in TCP client server

um use this code to store a received Image in the Hard disk Memory
i try to edit this code to store the received Image file in dynamic Image Object with out storing in the Hard disk Memory
private void StartReceiving()
{
try
{
string hstServer = Dns.GetHostName();
IPAddress ipaLocal ="127.0.0.1";
if (tlsServer == null)
{
tlsServer = new TcpListener(ipaLocal, Convert.ToInt32(txtPort.Text));
}
tlsServer.Start();
TcpClient tclServer = tlsServer.AcceptTcpClient();
strRemote = tclServer.GetStream();
int bytesSize = 0;
byte[] downBuffer = new byte[2048];
bytesSize = strRemote.Read(downBuffer, 0, 2048);
FileName = System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize);
try
{
strLocal = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}catch(Exception exp)
{
strLocal = new FileStream(FileName.Substring(0,5), FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}
downBuffer = new byte[2048];
bytesSize = strRemote.Read(downBuffer, 0, 2048);
downBuffer = new byte[2048];
while ((bytesSize = strRemote.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, bytesSize);
}
}
finally
{
strLocal.Close();
strRemote.Close();
}
}
edit by using CopyTo in .net 4
tlsServer.Start();
TcpClient tclServer = tlsServer.AcceptTcpClient();
tclServer.GetStream().CopyTo(ms);
//Get the image out of the stream
Image img = Image.FromStream(ms);
}
finally
{
m = Image.FromStream(strLocal);
strLocal.Close();
strRemote.Close();
}
As per the detail here:
MemoryStream ms = new MemoryStream();
//This call will block until the client disconnects though
tclServer.GetStream().CopyTo(ms);
//Get the image out of the stream
Image img = Image.FromStream(ms);

GZipStream and decompression

I have code that should do the compression:
FileStream fs = new FileStream("g:\\gj.txt", FileMode.Open);
FileStream fd = new FileStream("g:\\gj.zip", FileMode.Create);
GZipStream csStream = new GZipStream(fd, CompressionMode.Compress);
byte[] compressedBuffer = new byte[500];
int offset = 0;
int nRead;
nRead = fs.Read(compressedBuffer, offset, compressedBuffer.Length);
while (nRead > 0)
{
csStream.Write(compressedBuffer, offset, nRead);
offset = offset + nRead;
nRead = fs.Read(compressedBuffer, offset, compressedBuffer.Length);
}
fd.Close();
fs.Close();
and I think it does, but I want to decompress what was compressed the way above. I do somethink like that:
FileStream fd = new FileStream("g:\\gj.new", FileMode.Create);
FileStream fs = new FileStream("g:\\gj.zip", FileMode.Open);
GZipStream csStream = new GZipStream(fs, CompressionMode.Decompress);
byte[] decompressedBuffer = new byte[500];
int offset = 0;
int nRead;
nRead=csStream.Read(decompressedBuffer, offset, decompressedBuffer.Length);
while (nRead > 0)
{
fd.Write(decompressedBuffer, offset, nRead);
offset = offset + nRead;
nRead = csStream.Read(decompressedBuffer, offset, decompressedBuffer.Length);
}
fd.Close();
fs.Close();
and here it doesn't... I've got nRead = 0 befeore entering the loop... What I do wrong??
The test file I use is the simpliest TEXT file (size: 104 bytes)...
My first thought is that you haven't closed csStream. If you use using this happens automatically. Since gzip buffers data, you could be missing some.
Secondly; don't increment offset; that is the offset in the buffer (not the stream). Leave at 0:
using (Stream fs = File.OpenRead("gj.txt"))
using (Stream fd = File.Create("gj.zip"))
using (Stream csStream = new GZipStream(fd, CompressionMode.Compress))
{
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = fs.Read(buffer, 0, buffer.Length))> 0)
{
csStream.Write(buffer, 0, nRead);
}
}
using (Stream fd = File.Create("gj.new.txt"))
using (Stream fs = File.OpenRead("gj.zip"))
using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
{
byte[] buffer = new byte[1024];
int nRead;
while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0)
{
fd.Write(buffer, 0, nRead);
}
}
The two methods I have are like James Roland mentioned.
private static byte[] Compress(HttpPostedFileBase file)
{
using var to = new MemoryStream();
using var gZipStream = new GZipStream(to, CompressionMode.Compress);
file.InputStream.CopyTo(gZipStream);
gZipStream.Flush();
return to.ToArray();
}
private static byte[] Decompress(byte[] compressed)
{
using var from = new MemoryStream(compressed);
using var to = new MemoryStream();
using var gZipStream = new GZipStream(from, CompressionMode.Decompress);
gZipStream.CopyTo(to);
return to.ToArray();
}
However, I'm using an upload with
Request.Files[0]
then compress and save in the db. Then I pull the img out, decompress and set a src with
$"data:image/gif;base64,{ToBase64String(Decompress(img))}";

Categories

Resources