Download Image from URL

đoạn code trên sử dụng để download một hình ảnh về

/// <summary>
/// Function to download Image from website
/// </summary>
/// <param name="_URL">URL address to download image</param>
/// <returns>Image</returns>
public Image DownloadImage(string _URL)
{
    Image _tmpImage = null;

    try
    {
        // Open a connection
        System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(_URL);

        _HttpWebRequest.AllowWriteStreamBuffering = true;

        // You can also specify additional header values like the user agent or the referer: (Optional)
        _HttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
        _HttpWebRequest.Referer = "http://www.google.com/";

        // set timeout for 20 seconds (Optional)
        _HttpWebRequest.Timeout = 20000;

        // Request response:
        System.Net.WebResponse _WebResponse = _HttpWebRequest.GetResponse();

        // Open data stream:
        System.IO.Stream _WebStream = _WebResponse.GetResponseStream();

        // convert webstream to image
        _tmpImage = Image.FromStream(_WebStream);

        // Cleanup
        _WebResponse.Close();
        _WebResponse.Close();
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        return null;
    }

    return _tmpImage;
}
Các sử dụng
// Download web image
Image _Image = null;
_Image = DownloadImage("http://www.yourdomain.com/sample-image.jpg");

// check for valid image
if (_Image != null)
{
    // show image in picturebox
    pictureBox1.Image = _Image;

    // lets save image to disk
    _Image.Save(@"C:\SampleImage.jpg");
}

Download File from URL

Đoạn code này sử dụng để down một file trên internet

/// <summary>
/// Function to download a file from URL and save it to local drive
/// </summary>
/// <param name="_URL">URL address to download file</param>
public void DownloadFile(string _URL, string _SaveAs)
{
    try
    {
        System.Net.WebClient _WebClient = new System.Net.WebClient();
        // Downloads the resource with the specified URI to a local file.
        _WebClient.DownloadFile(_URL, _SaveAs);
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }
}

Sử dụng

DownloadFile("http://www.yourdomain.com/sample-file.zip", @"C:\sample-file.zip");

Sử dụng tiếp tính down load

// Occurs when an asynchronous file download operation completes.
private void _DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
    // File download completed
    download_button.Enabled = Enabled;
    MessageBox.Show("Download completed");
}

// Occurs when an asynchronous download operation successfully transfers some or all of the data.
private void _DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
    // Update progress bar
    progressBar1.Value = e.ProgressPercentage;
}


// download button click event
private void download_button_Click(object sender, EventArgs e)
{
    // Disable download button to avoid clicking again while downloading the file
    download_button.Enabled = false;

    // Downloads, to a local file, the resource with the specified URI. 
    // This method does not block the calling thread.
    System.Net.WebClient _WebClient = new System.Net.WebClient();
    _WebClient.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted);
    _WebClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(_DownloadProgressChanged);
    _WebClient.DownloadFileAsync(new Uri("http://www.youdomain.com/sample-file.zip"), @"C:\sample-file.zip");
}

 

Lưu một đối đượng [object] thành một file

Đoạn code này thích hợp để tạo một database để lưu những đối tượng cần lưu có thể sử dụng như cache vậy

/// <summary>
/// Function to save object to external file
/// </summary>
/// <param name="_Object">object to save</param>
/// <param name="_FileName">File name to save object</param>
/// <returns>Return true if object save successfully, if not return false</returns>
public bool ObjectToFile(object _Object, string _FileName)
{
    try
    {
        // create new memory stream
        System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();

        // create new BinaryFormatter
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
                    = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        // Serializes an object, or graph of connected objects, to the given stream.
        _BinaryFormatter.Serialize(_MemoryStream, _Object);

        // convert stream to byte array
        byte[] _ByteArray = _MemoryStream.ToArray();

        // Open file for writing
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);

        // Writes a block of bytes to this stream using data from a byte array.
        _FileStream.Write(_ByteArray.ToArray(), 0, _ByteArray.Length);

        // close file stream
        _FileStream.Close();

        // cleanup
        _MemoryStream.Close();
        _MemoryStream.Dispose();
        _MemoryStream = null;
        _ByteArray = null;

        return true;
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    // Error occured, return null
    return false;
}

Sử dụng:

ObjectToFile(pictureBox1.Image, "c:\\image-object.dat");

Lấy thông tin IP của máy local

 

/// <summary>
/// Gets IP addresses of the local computer
/// </summary>
public string GetLocalIP()
{
    string _IP = null;

    // Resolves a host name or IP address to an IPHostEntry instance.
    // IPHostEntry - Provides a container class for Internet host address information. 
    System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

    // IPAddress class contains the address of a computer on an IP network. 
    foreach (System.Net.IPAddress _IPAddress in _IPHostEntry.AddressList)
    {
        // InterNetwork indicates that an IP version 4 address is expected 
        // when a Socket connects to an endpoint
        if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
        {
            _IP = _IPAddress.ToString();
        }
    }
    return _IP;
}

 

Ví dụ sử dụng:

 

Console.WriteLine("Local computer IP address : " + GetLocalIP());

Đoạn code này sử dụng để lấy ip của máy có nhiều địa chỉ ip

/// <summary>
/// Gets IP addresses object list from the local computer
/// </summary>
public System.Net.IPAddress[] GetLocalIPList()
{
    // Resolves a host name or IP address to an IPHostEntry instance.
    // IPHostEntry - Provides a container class for Internet host address information. 
    System.Net.IPHostEntry _IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());

    return _IPHostEntry.AddressList;
}

Ví dụ sử dụng:

// display all IP addresses of local machine
foreach (System.Net.IPAddress _IPAddress in GetLocalIPList())
    Console.WriteLine(_IPAddress.ToString());


// display all IP addresses of local machine with addressing scheme
foreach (System.Net.IPAddress _IPAddress in GetLocalIPList())
    Console.WriteLine(_IPAddress.AddressFamily.ToString() + " = " +  _IPAddress.ToString());

 

Tách các thẻ img bằng RegularExpressions

//  using System.Text.RegularExpressions;

/// <summary>
///  Regular expression built for C# on: Mon, Nov 22, 2010, 03:51:18 PM
///  Using Expresso Version: 3.0.2766, http://www.ultrapico.com
///  
///  A description of the regular expression:
///  
///  <img src="
///      <img
///      Space
///      src="
///  Any character that is NOT in this class: ["], any number of repetitions
///  " alt="
///      "
///      Space
///      alt="
///  [1]: A numbered capture group. [[^"]*]
///      Any character that is NOT in this class: ["], any number of repetitions
///  ">
///      ">
///  
///
/// </summary>
public static Regex regex = new Regex(
      "<img src=\"[^\"]*\" alt=\"([^\"]*)\">",
      RegexOptions.Compiled
    );


// This is the replacement string
public static string regexReplace = "$1";


//// Replace the matched text in the InputText using the replacement pattern
// string result = regex.Replace(InputText,regexReplace);

//// Split the InputText wherever the regex matches
// string[] results = regex.Split(InputText);

//// Capture the first Match, if any, in the InputText
// Match m = regex.Match(InputText);

//// Capture all Matches in the InputText
// MatchCollection ms = regex.Matches(InputText);

//// Test to see if there is a match in the InputText
// bool IsMatch = regex.IsMatch(InputText);

//// Get the names of all the named and numbered capture groups
// string[] GroupNames = regex.GetGroupNames();

//// Get the numbers of all the named and numbered capture groups
// int[] GroupNumbers = regex.GetGroupNumbers();