Pages

Thursday, July 11, 2013

Simple task (thread) implementation in C# .NET 4.0 and 4.5

This code implements a simple way to start a method in a thread and wait for it to end to get the return value of the method.



System.Threading.Tasks.Task<string> task =
 System.Threading.Tasks.Task.Factory.StartNew(() => myMethod(myString));

if (task.Status == System.Threading.Tasks.TaskStatus.RanToCompletion)
{
 //is done, do something!
 //use result task.Result
}

I Forgot My Administrator Password in Windows XP!

This guide could help you to reset the Administrator password in Windows XP without knowing it. Require a Windows XP boot CD.

I Forgot My Administrator Password!

How to get image from url i C# .NET

A very simple one liner to fetch an image from an url in C#


System.Drawing.Image.FromStream(new WebClient().OpenRead(imageUrl)); 

How to compress and decompress files in C# .NET 4.0 (GZip)

.NET 4.0 has a built-in gzip compress and decompress method.
.NET 4.5 has zip support.

This code shows how to use the .NET 4.0 gzip functionality. This also includes .NET 4.0 Client Profile
.NET 4.0 is supported by Windows XP and .NET 4.5 is NOT.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static void Decompress(FileInfo file)
{
 using (FileStream inFile = file.OpenRead())
 {
  //original file extension, ex. filename.exe.gz
  string orgName =
   file.FullName.Remove(file.FullName.Length - file.Extension.Length);

  //decompress file
  using (FileStream outFile = File.Create(orgName))
  {
   using (GZipStream Decompress = new GZipStream(inFile,
     CompressionMode.Decompress))
   {
    //write decompressed file
    byte[] buffer = new byte[4096];
    int index;
    while ((index = Decompress.Read(buffer, 0, buffer.Length)) != 0)
     outFile.Write(buffer, 0, index);
   }
  }
 }
}

public static void Compress(FileInfo file)
{
 using (FileStream inFile = file.OpenRead())
 {
  //create target file
  using (FileStream outFile =File.Create(file.FullName + ".gz"))
  {
   using (GZipStream Compress = new GZipStream(outFile,
     CompressionMode.Compress))
   {
    //write compressed file
    byte[] buffer = new byte[4096];
    int index;
    while ((index = inFile.Read(buffer, 0, buffer.Length)) != 0)
     Compress.Write(buffer, 0, index);
   }
  }
 }
}