C# code to publish, delete, retrieve tweets using oauth

The following C#.net class can be used to update statuses, delete, retweet statuses, obtain information regarding a particular status and any body who retweeted a particular status using status id.

This class implements all the methods that are under the “Tweets Resources” section in Twitter API documentation

 

using System;
using System.Text;
using System.Collections.Generic;

namespace TwitterAPI
{
    public class Tweets
    {
        #region Class-Level-Declarations

        private oAuthTwitter OAuth;
        /// <summary>
        /// Create, Update, retrieve, delete tweets(status messages) using this class
        /// </summary>
        /// <param name="_oauth">An authorized and authenticated oAuth token</param>
        public Tweets(oAuthTwitter _oauth)
        {
            this.OAuth = _oauth;
        }
        public enum ResponseFormat { JSON, XML };

        #endregion

        #region Show:ID

        /// <summary>
        /// Returns a single status, specified by the id parameter below. The status's author will be returned inline.
        /// This does not require authentication as long as the status is not protected
        /// This is a rate limited call
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_By_ID(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/show/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Update

        /// <summary>
        /// Updates the authenticating user's status. A status update with text identical to the authenticating user's current status will be ignored to prevent duplicates.
        /// Authentication is required and this call is not rate limited
        /// </summary>
        /// <param name="tweet_message">The text of your status update, up to 140 characters.</param>
        /// <param name="reponse_format">The format in which you want twitter to respond</param>
        /// <param name="optionalparameters">Any optional paramters you want to pass</param>
        /// <returns>Response string from twitter in user selected format </returns>
        public string UpdateStatus(ResponseFormat reponse_format, string tweet_message, string optionalparameters)
        {
            if (string.IsNullOrEmpty(tweet_message))
                throw new ArgumentNullException(tweet_message, "The status message cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/update." + reponse_format.ToString(), "status=" + tweet_message + optionalparameters);
        }

         #endregion

        #region Destroy:Id

        /// <summary>
        /// Destroys the status specified by the required ID parameter.In other words deletes the specified tweet
        /// Requires authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Destroy_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/destroy/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Retweet:Id

        /// <summary>
        /// Retweets a tweet. Returns the original tweet with retweet details embedded.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Retweet_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.POST, "http://api.twitter.com/1/statuses/retweet/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweets:Id

        /// <summary>
        ///Returns up to 100 of the first retweets of a given tweet.
        /// Does not require authentication, and rate limited is false
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweets_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/retweets/" + statusid + "." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user objects of up to 100 members who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by." + response_format.ToString(), optionalparameters);
        }

        #endregion

        #region Show Retweeted By:Id

        /// <summary>
        /// Show user ids of up to 100 users who retweeted the status.
        /// Requires authentication, and rate limited
        /// </summary>
        /// <param name="response_format">The format in which you want twitter to respond</param>
        /// <param name="statusid">The numerical ID of the desired status.</param>
        /// <param name="optionalparameters">Any other optional parameters.Use an empty string if you dont want to pass any optional parameters</param>
        /// <returns>Response string from twitter in user selected format</returns>
        public string Show_Retweetedby_By_Id(ResponseFormat response_format, string statusid, string optionalparameters)
        {
            if (string.IsNullOrEmpty(statusid))
                throw new ArgumentNullException(statusid, "Status Id cannot be null");
            return OAuth.oAuthWebRequest(oAuthTwitter.Method.GET, "http://api.twitter.com/1/statuses/" + statusid + "/retweeted_by/ids." + response_format.ToString(), optionalparameters);
        }        #endregion
    }
}

 

This class file uses OAuth implementation by shannon whitley (for more information see my previous post Implementing oauth twitter search in C# and JSON).

You can download the complete source code along with this class from https://sites.google.com/site/coderbuddy/downloads/TwitterAPI.zip?attredirects=0&d=1

TwitterAPI.zip (43,25 kb)

Kiểm tra máy tính có kết nối hay không

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace Coderbuddy
{

    public class CheckInternetConnection
    {
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);



        public bool IsInternetConnectionAvailable()
        {
            int Desc;
            return InternetGetConnectedState(out Desc, 0);
        }
    }
}

Upload hình lên imageshack.us sử dụng C#

 

using System;
using System.IO;
using System.Web;
using System.Net;
using System.Text;
using System.Drawing;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace Imageshack
{
  public class ImageshackAPI
  {
    public string Upload(string fileName)
    {
      try
      {
        string contentType = "image/jpeg"; ;
        CookieContainer cookie = new CookieContainer();
        NameValueCollection par = new NameValueCollection();
        par["MAX_FILE_SIZE"] = "3145728";
        par["refer"] = "";
        par["brand"] = "";
        par["key"] = "YOUR API Key";
        par["optimage"] = "1";
        par["rembar"] = "1";
        par["submit"] = "host it!";
        List<string> l = new List<string>();
        string resp;
        par["optsize"] = "resample";
        resp = UploadFileEx(fileName, "http://www.imageshack.us/upload_api.php", "fileupload", contentType, par, cookie);
        return resp;
      }
      catch (Exception ex)
      {
        return ex.Message;
      }
    }

    private string UploadFileEx(string uploadfile, string url, string fileFormName, string contenttype, NameValueCollection querystring, CookieContainer cookies)
    {
      if ((fileFormName == null) ||
        (fileFormName.Length == 0))
      {
        fileFormName = "fileupload";
      }

      if ((contenttype == null) ||
        (contenttype.Length == 0))
      {
        contenttype = "application/octet-stream";
      }


      string postdata;
      postdata = "?";
      if (querystring != null)
      {
        foreach (string key in querystring.Keys)
        {
          postdata += key + "=" + querystring.Get(key) + "&";
        }
      }
      Uri uri = new Uri(url + postdata);


      string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
      HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
      webrequest.CookieContainer = cookies;
      webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
      webrequest.Method = "POST";


      // Build up the post message header
      StringBuilder sb = new StringBuilder();
      sb.Append("--");
      sb.Append(boundary);
      sb.Append("\r\n");
      sb.Append("Content-Disposition: form-data; name=\"");
      sb.Append(fileFormName);
      sb.Append("\"; filename=\"");
      sb.Append(Path.GetFileName(uploadfile));
      sb.Append("\"");
      sb.Append("\r\n");
      sb.Append("Content-Type: ");
      sb.Append(contenttype);
      sb.Append("\r\n");
      sb.Append("\r\n");

      string postHeader = sb.ToString();
      byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

      // Build the trailing boundary string as a byte array
      // ensuring the boundary appears on a line by itself
      byte[] boundaryBytes =
          Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

      FileStream fileStream = new FileStream(uploadfile,
                    FileMode.Open, FileAccess.Read);
      long length = postHeaderBytes.Length + fileStream.Length +
                          boundaryBytes.Length;
      webrequest.ContentLength = length;

      Stream requestStream = webrequest.GetRequestStream();

      // Write out our post header
      requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

      // Write out the file contents
      byte[] buffer = new Byte[checked((uint)Math.Min(4096,
                   (int)fileStream.Length))];
      int bytesRead = 0;
      while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        requestStream.Write(buffer, 0, bytesRead);

      // Write out the trailing boundary
      requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
      WebResponse responce = webrequest.GetResponse();
      Stream s = responce.GetResponseStream();
      XmlSerializer xSerializer = new XmlSerializer(typeof(imginfo));
      imginfo ii = (imginfo)xSerializer.Deserialize(s);
      imginfoLinks ifl = ii.links;
      fileStream.Close();
      s.Close();
      return ifl.image_link;


    }
  }
}

the following is the XML deserialization class used in the above class



using System.Xml.Serialization;

namespace Imageshack
{

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://ns.imageshack.us/imginfo/7/", IsNullable = false)]
  public partial class imginfo
  {

    private imginfoRating ratingField;

    private imginfoFiles filesField;

    private imginfoResolution resolutionField;

    private string classField;

    private string visibilityField;

    private imginfoUploader uploaderField;

    private imginfoLinks linksField;

    private byte versionField;

    private uint timestampField;

    /// <remarks/>
    public imginfoRating rating
    {
      get
      {
        return this.ratingField;
      }
      set
      {
        this.ratingField = value;
      }
    }

    /// <remarks/>
    public imginfoFiles files
    {
      get
      {
        return this.filesField;
      }
      set
      {
        this.filesField = value;
      }
    }

    /// <remarks/>
    public imginfoResolution resolution
    {
      get
      {
        return this.resolutionField;
      }
      set
      {
        this.resolutionField = value;
      }
    }

    /// <remarks/>
    public string @class
    {
      get
      {
        return this.classField;
      }
      set
      {
        this.classField = value;
      }
    }

    /// <remarks/>
    public string visibility
    {
      get
      {
        return this.visibilityField;
      }
      set
      {
        this.visibilityField = value;
      }
    }

    /// <remarks/>
    public imginfoUploader uploader
    {
      get
      {
        return this.uploaderField;
      }
      set
      {
        this.uploaderField = value;
      }
    }

    /// <remarks/>
    public imginfoLinks links
    {
      get
      {
        return this.linksField;
      }
      set
      {
        this.linksField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte version
    {
      get
      {
        return this.versionField;
      }
      set
      {
        this.versionField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public uint timestamp
    {
      get
      {
        return this.timestampField;
      }
      set
      {
        this.timestampField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoRating
  {

    private byte ratingsField;

    private decimal avgField;

    /// <remarks/>
    public byte ratings
    {
      get
      {
        return this.ratingsField;
      }
      set
      {
        this.ratingsField = value;
      }
    }

    /// <remarks/>
    public decimal avg
    {
      get
      {
        return this.avgField;
      }
      set
      {
        this.avgField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoFiles
  {

    private imginfoFilesImage imageField;

    private imginfoFilesThumb thumbField;

    private ushort serverField;

    private ushort bucketField;

    /// <remarks/>
    public imginfoFilesImage image
    {
      get
      {
        return this.imageField;
      }
      set
      {
        this.imageField = value;
      }
    }

    /// <remarks/>
    public imginfoFilesThumb thumb
    {
      get
      {
        return this.thumbField;
      }
      set
      {
        this.thumbField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort server
    {
      get
      {
        return this.serverField;
      }
      set
      {
        this.serverField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort bucket
    {
      get
      {
        return this.bucketField;
      }
      set
      {
        this.bucketField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoFilesImage
  {

    private ushort sizeField;

    private string contenttypeField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort size
    {
      get
      {
        return this.sizeField;
      }
      set
      {
        this.sizeField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
    public string contenttype
    {
      get
      {
        return this.contenttypeField;
      }
      set
      {
        this.contenttypeField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value
    {
      get
      {
        return this.valueField;
      }
      set
      {
        this.valueField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoFilesThumb
  {

    private ushort sizeField;

    private string contenttypeField;

    private string valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort size
    {
      get
      {
        return this.sizeField;
      }
      set
      {
        this.sizeField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute("content-type")]
    public string contenttype
    {
      get
      {
        return this.contenttypeField;
      }
      set
      {
        this.contenttypeField = value;
      }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlTextAttribute()]
    public string Value
    {
      get
      {
        return this.valueField;
      }
      set
      {
        this.valueField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoResolution
  {

    private ushort widthField;

    private ushort heightField;

    /// <remarks/>
    public ushort width
    {
      get
      {
        return this.widthField;
      }
      set
      {
        this.widthField = value;
      }
    }

    /// <remarks/>
    public ushort height
    {
      get
      {
        return this.heightField;
      }
      set
      {
        this.heightField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoUploader
  {

    private string ipField;

    /// <remarks/>
    public string ip
    {
      get
      {
        return this.ipField;
      }
      set
      {
        this.ipField = value;
      }
    }
  }

  /// <remarks/>
  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")]
  [System.SerializableAttribute()]
  [System.Diagnostics.DebuggerStepThroughAttribute()]
  [System.ComponentModel.DesignerCategoryAttribute("code")]
  [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://ns.imageshack.us/imginfo/7/")]
  public partial class imginfoLinks
  {

    private string image_linkField;

    private string image_htmlField;

    private string image_bbField;

    private string image_bb2Field;

    private string thumb_linkField;

    private string thumb_htmlField;

    private string thumb_bbField;

    private string thumb_bb2Field;

    private string yfrog_linkField;

    private string yfrog_thumbField;

    private string ad_linkField;

    private string done_pageField;

    /// <remarks/>
    public string image_link
    {
      get
      {
        return this.image_linkField;
      }
      set
      {
        this.image_linkField = value;
      }
    }

    /// <remarks/>
    public string image_html
    {
      get
      {
        return this.image_htmlField;
      }
      set
      {
        this.image_htmlField = value;
      }
    }

    /// <remarks/>
    public string image_bb
    {
      get
      {
        return this.image_bbField;
      }
      set
      {
        this.image_bbField = value;
      }
    }

    /// <remarks/>
    public string image_bb2
    {
      get
      {
        return this.image_bb2Field;
      }
      set
      {
        this.image_bb2Field = value;
      }
    }

    /// <remarks/>
    public string thumb_link
    {
      get
      {
        return this.thumb_linkField;
      }
      set
      {
        this.thumb_linkField = value;
      }
    }

    /// <remarks/>
    public string thumb_html
    {
      get
      {
        return this.thumb_htmlField;
      }
      set
      {
        this.thumb_htmlField = value;
      }
    }

    /// <remarks/>
    public string thumb_bb
    {
      get
      {
        return this.thumb_bbField;
      }
      set
      {
        this.thumb_bbField = value;
      }
    }

    /// <remarks/>
    public string thumb_bb2
    {
      get
      {
        return this.thumb_bb2Field;
      }
      set
      {
        this.thumb_bb2Field = value;
      }
    }

    /// <remarks/>
    public string yfrog_link
    {
      get
      {
        return this.yfrog_linkField;
      }
      set
      {
        this.yfrog_linkField = value;
      }
    }

    /// <remarks/>
    public string yfrog_thumb
    {
      get
      {
        return this.yfrog_thumbField;
      }
      set
      {
        this.yfrog_thumbField = value;
      }
    }

    /// <remarks/>
    public string ad_link
    {
      get
      {
        return this.ad_linkField;
      }
      set
      {
        this.ad_linkField = value;
      }
    }

    /// <remarks/>
    public string done_page
    {
      get
      {
        return this.done_pageField;
      }
      set
      {
        this.done_pageField = value;
      }
    }
  }
}

 

Viết bài trên Twitter API sử dụng c#

[OperationContract]
public void SubmitUserStatus(string username, string tweet)
{
    // encode the username/password
    string user = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
    // determine what we want to upload as a status
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes("status=" + tweet);
    // connect with the update page
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://twitter.com/statuses/update.xml");
    // set the method to POST
    request.Method = "POST";
    // thanks to argodev for this recent change!
    request.ServicePoint.Expect100Continue = false;
    // set the authorisation levels
    request.Headers.Add("Authorization", "Basic " + user);
    request.ContentType = "application/x-www-form-urlencoded";
    // set the length of the content
    request.ContentLength = bytes.Length;
    // set up the stream
    Stream reqStream = request.GetRequestStream();
    // write to the stream
    reqStream.Write(bytes, 0, bytes.Length);
    // close the stream
    reqStream.Close();
}

How to simple read CSV file in C#

Cần sử dụng thử viện

Using System.IO;
Đây là đoạn code đọc file CSV
StreamReader sr = new StreamReader(@"file.csv");
// for set encoding
// StreamReader sr = new StreamReader(@"file.csv", Encoding.GetEncoding(1250));

string strline = "";
string[] _values = null;
int x = 0;
while (!sr.EndOfStream)
{
    x++;
    strline = sr.ReadLine();
    _values = strline.Split(';');
    if (_values.Length >= 6 && _values[0].Trim().Length>0)
    {
      MessageBox.show(_values[1]);
    }
}
sr.Close();