• CodeProject Some Cool Tips for .NET之二


    初试翻译,水平有限,还望见亮。
    .NET Framework
    #1. How to get the path for "My Documents" and other system folders?
    如何获取‘我的文档’等一些系统文件夹的路径?
    Use the GetFolderPath method of the System.Environment class to retrieve this information.
    使用System.Environment类的GetFolderPath方法来检索这些信息。
    Code:
        MessageBox.Show( Environment.GetFolderPath( Environment.SpecialFolder.Personal ) );

    #2. How to get the path to my running EXE?
    如何获取EXE程序当前执行的路径?
    The Application class has a static member ExecutablePath that has this information.
    通过调用类Application中的静态成员属性ExecutablePath来获取这些信息。
    Code:
        string appPath = Application.ExecutablePath;
    Alternative: 备选方法 通过反射机制实现(动态获取程序集信息)
    Code:
        System.Reflection.Assembly.GetExecutingAssembly().Location

    #3. How to determine which operating system is running?
    如何确定当前运行的操作系统?
    Use System.Environment's OSVersion static (shared) property.
    通过调用System.Environment类的静态(共享)属性来获取
    Code:
         OperatingSystem os = Environment.OSVersion;
         MessageBox.Show(os.Version.ToString());
         MessageBox.Show(os.Platform.ToString());

    #4. How to get a file's name from the complete path string?
    如何从完整的路径中获取文件名?
    Use System.IO.Path.GetFileName and System.IO.Path.GetFileNameWithoutExtension static methods.
    通过System.IO.Path.GetFileName 和 System.IO.Path.GetFileNameWithoutExtension(无扩展名)静态方法获取。

    #5. How to get a file's extension from the complete path string?
    如何从完整的路径中获取文件扩展名?
    Use System.IO.Path.GetExtension static method.
    通过System.IO.Path.GetExtension静态方法获取。

    #6. What is difference beween VB.NET and C#.NET?
    VB.NET与C#.NET之间的区别是什么?
    Hi friends, click here to find the best comparison ever between VB.NET and C#.NET .
    朋友,请点击这儿(http://download.microsoft.com/download/6/3/5/6354bf47-c597-4029-89e9-2495e7539ab9/vbcsharpwp.exe)找出最佳对比答案。

    #7. How to find whether your system has mouse or the number of buttons, whether it has wheel, or whether the mouse buttons are swapped or size of your monitor and many such information?

    如何找出你的系统中是否有鼠标,有几个按键,是否有滚轮,鼠标按键是否有交换和监视器的大小等等信息。
    Use System.Windows.Forms.SystemInformation.
      下载源文件-8 .65KB(http://www.codeproject.com/KB/miscctrl/tips/Tip23_src.zip)
      下载演示项目-4 .60KB (http://www.codeproject.com/KB/miscctrl/tips/Tip23_demo.zip)
    SystemInformation provides static (Shared in Visual Basic) methods and properties that can be used to get information such as Windows display element sizes, operating system settings, network availability, and the capabilities of hardware installed on the system.This class cannot be instantiated. e.g
    使用System.Windows.Forms.SystemInformation类的静态方法与属性得到各种系统信息,例如:显示器分辨率、操作系统设置、网络联通情况、硬件配置。此类不能被实例化。
    获取鼠标的是:
    Code:
        MousePresent:    SystemInformation.MousePresent.ToString()
        MouseButtonsSwapped:   SystemInformation.MouseButtonsSwapped.ToString()

    #8. What is the purpose of the [STA Thread] attribute for the Main method of a C# program?
    C#程序的主函数写[STA Thread]属性的目的是什么?
    That marks the thread as being Single Thread Apartment which means any multiple threaded calls need to be marshaled over to that thread before they are called. That's there because Windows Forms uses some OLE calls(Clipboard for example), which must be made from the thread that initialized OLE.
    多线程调用(单线程套间)单线程前都需要编组排列。因为Windows窗体使用了一些OLE调用(例如剪贴板),调用之前必须先初始化OLE。
    单线程套间,简单来说所有对于单线程套间中对象的访问都是通过消息来传递的,所以同一时间只有一个线程能够访问单线程套间中的对象。

    #9. How to import CSV data using .NET application?
    如何使用.NET应用程序导入CSV数据?
       下载源文件-8 .65KB(http://www.codeproject.com/KB/database/FinalCSVReader/FinalCSVReader_src.zip)
       下载演示项目-4 .60KB (http://www.codeproject.com/KB/miscctrl/tips/Freespace_demo.zip)
    <img src="http://www.codeproject.com/KB/database/FinalCSVReader/FinalCSVReader.jpg"></img>
    Introduction
    Nowadays it is common in applications to have the functionality of reading the CSV data. My current project needed one. Even after searching for long, I could not get one which could satisfy my requirements. But after doing considerable amount of study, I came up with the following tool. CSV files stand for Comma Separated Value files. They are common text files with comma delimited values. Though the default delimiter is comma (,), we can specify other characters as delimiters like the semi-colon (;), colon (:), asterisk (*). But you cannot specify double quotes (") as a delimiter. I have used Microsoft Text Drivers for reading the CSV data. You have to use ODBC connection for accessing the CSV data. You can either create a DSN or use the connection string. If you create a DSN, the schema.ini file gets created automatically in the folder where all your CSV files reside. But if you use connection string, you have to create schema.ini file on your own. We are going to see the latter approach.
    Schema.ini File (Text File Driver)

    When the Text driver is used, the format of the text file is determined by using a schema information file. The schema information file, which is always named schema.ini and always kept in the same directory as the text data source, provides the IISAM with information about the general format of the file, the column name and data type information, and a number of other data characteristics.
    Using the demo application

    For successfully running the application you need Test.csv file and a database with a table having three columns. But all this is provided in the demo application. So you need not worry. Follow these steps to run the demo application:

       1. First run DBI.exe application.
       2. The screen shown below will appear.
       3. Fill the required details and click the button "Install".
       4. Make sure that a folder named "Test" is created in "D:" drive with the Test.csv file in it.
       5. Now run our main application i.e. FinalCSVReader.exe.
       6. Keep the default folder and file path as it is.
       7. First click "Import CSV data" to import the CSV data.
       8. Now click "Save", to save the data in the database.
    <img src="http://www.codeproject.com/KB/database/FinalCSVReader/DBInstaller.jpg"></img>
    Using the source code
    Some important parts of the code are discussed below
    Create schema.ini

    This is a function writeSchema(). It creates the schema.ini file dynamically.
    Code:
       /*Schema.ini File (Text File Driver)
     When the Text driver is used, the format of the
     text file is determined by using a schema information
     file. The schema information file, which is always named
     Schema.ini and always kept in the same directory as the
     text data source, provides the IISAM with information
     about the general format of the file, the column name
     and data type information, and a number of other data
     characteristics*/

    private void writeSchema()
    {
     try    
        {
            FileStream fsOutput =
                 new FileStream (txtCSVFolderPath.Text+"\\schema.ini",
                                     FileMode.Create, FileAccess.Write);
            StreamWriter srOutput = new StreamWriter (fsOutput);
            string s1, s2, s3,s4,s5;
            s1="["+strCSVFile+"]";
            s2="ColNameHeader="+bolColName.ToString ();
            s3="Format="+strFormat;
            s4="MaxScanRows=25";
            s5="CharacterSet=OEM";
            srOutput.WriteLine(s1.ToString()+'\n'+s2.ToString()+
                                        '\n'+s3.ToString()+'\n'+
                                        s4.ToString()+'\n'+s5.ToString());
            srOutput.Close ();
            fsOutput.Close ();                    
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
        }

    Function for importing the CSV Data

    This function ConnectCSV (string filetable) takes the .csv file name as argument and returns the dataset containing the imported data.
    Code:
    public DataSet ConnectCSV (string filetable)
    {
      DataSet ds = new DataSet ();
      try
       {        
           /* You can get connected to driver either by using
           DSN or connection string. Create a connection string
           as below, if you want to use DSN less connection.
           The DBQ attribute sets the path of directory which
           contains CSV files*/

           string strConnString=
                 "Driver={Microsoft Text Driver (*.txt;*.csv)};
                 Dbq="+txtCSVFolderPath.Text.Trim()+";
                 Extensions=asc,csv,tab,txt;
                 Persist Security Info=False";

           string sql_select;                                
           System.Data.Odbc.OdbcConnection conn;        
            
           //Create connection to CSV file

           conn = new System.Data.Odbc.OdbcConnection(
                                        strConnString.Trim ());

           // For creating a connection using DSN, use following line

           //conn = new System.Data.Odbc.OdbcConnection(DSN="MyDSN");

        
           //Open the connection

           conn.Open ();
           //Fetch records from CSV

           sql_select="select * from ["+ filetable +"]";
                    
           obj_oledb_da=new System.Data.Odbc.OdbcDataAdapter(
                                                    sql_select,conn);
           //Fill dataset with the records from CSV file

           obj_oledb_da.Fill(ds,"Stocks");
                    
           //Set the datagrid properties

                    
           dGridCSVdata.DataSource=ds;
           dGridCSVdata.DataMember="Stocks";
           //Close Connection to CSV file

           conn.Close ();                
       }
       catch (Exception e) //Error

       {
           MessageBox.Show (e.Message);
       }
       return ds;
    }
    Code for inserting the data

    This is a code written in the button's click event btnUpload_Click. This actually inserts the data in the database.
    Code:
    private void btnUpload_Click(object sender,
                                    System.EventArgs e)
    {
     try
      {
        // Create an SQL Connection

        // You can use actual connection

        // string instead of ReadConFile()


        SqlConnection  con1=
             new SqlConnection(ReadConFile().Trim());
        SqlCommand cmd = new SqlCommand();
        SqlCommand cmd1 = new SqlCommand();

        // Create Dataset                    

        DataSet da = new DataSet();

        /* To actually fill the dataset,
        Call the function ImportCSV and   assign
        the returned dataset to new dataset as below */

        da=this.ConnectCSV(strCSVFile);    

        /* Now we will collect data from data table
        and insert it into database one by one.
        Initially there will be no data in database
        so we will insert data in first two columns
        and after that we will update data in same row
        for remaining columns. The logic is simple.
        'i' represents rows while 'j' represents columns*/

        cmd.Connection=con1;
        cmd.CommandType=CommandType.Text;
        cmd1.Connection=con1;
        cmd1.CommandType=CommandType.Text;
                        
        con1.Open();
        for(int i=0;i<=da.Tables["Stocks"].Rows.Count-1;i++)
        {                        
          for(int j=1;j<=da.Tables["Stocks"].Columns.Count-1;j++)
          {
            cmd.CommandText=
              "Insert  into Test(srno,
                 "+da.Tables["Stocks"].Columns[0].ColumnName.Trim()+")
              values("+(i+1)+",
                 '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(0)+"')";
            
            /* For UPDATE statement, in where clause you
            need some unique row identifier. We are using
            ‘srno’ in WHERE clause. */

            cmd1.CommandText=
              "Update Test set "
                  +da.Tables["Stocks"].Columns[j].ColumnName.Trim()+"
                  = '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j)+
              "' where srno ="+(i+1);                            
            cmd.ExecuteNonQuery();
            cmd1.ExecuteNonQuery();                            
          }
        }
        con1.Close();
      }
      catch(Exception ex)
      {
          MessageBox.Show(ex.Message);
      }
      finally
      {
          btnUpload.Enabled=false;
      }
    }

    #10. How to find size of logical drives using .NET?
    如何使用.Net找出逻辑驱动的大小?
       下载源文件-8 .65KB(http://www.codeproject.com/KB/miscctrl/tips/Freespace_src.zip)
       下载演示项目-4 .60KB (http://www.codeproject.com/KB/database/FinalCSVReader/FinalCSVReader_demo.zip)
    <img src="http://www.codeproject.com/KB/miscctrl/tips/Freespace.jpgg"></img>
    There is direct method in .NET for computing the file size but there is no such method for computing directory size and logical drive size.One may think of just adding file size to get directory size and then drive size. But this method has some drawbacks. But we can use Win32 API function GetDiskFreeSpaceEx for this purpose.
    The GetDiskFreeSpaceEx function retrieves information about the amount of space that is available on a disk volume, which is the total amount of space, the total amount of free space, and the total amount of free space available to the user that is associated with the calling thread. You can do it as following: Enlist the drives:
    Code:
    string[] tempString = Directory.GetLogicalDrives();
    foreach(string tempDrive in tempString)    
     {
       cmbDrives.Items.Add(tempDrive);
     }
    cmbDrives.SelectedIndex=0;

    public sealed class DriveInfo
      {
         
     [DllImport("kernel32.dll", EntryPoint="GetDiskFreeSpaceExA")]
     private static extern long GetDiskFreeSpaceEx(string lpDirectoryName,
     out long lpFreeBytesAvailableToCaller,
     out long lpTotalNumberOfBytes,
     out long lpTotalNumberOfFreeBytes);
         
    public static long GetInfo(string drive, out long available, out long total, out long free)
      {
        return GetDiskFreeSpaceEx(drive,out available,out total,out free);
      }
         
    public static DriveInfoSystem GetInfo(string drive)
     {
      long result, available, total, free;
      result = GetDiskFreeSpaceEx(drive, out available, out total, out free);
      return new DriveInfoSystem(drive,result,available,total,free);
      }
         
    }

    public struct DriveInfoSystem
     {      
      public readonly string Drive;
      public readonly long Result;
      public readonly long Available;
      public readonly long Total;
      public readonly long Free;

    public DriveInfoSystem(string drive, long result, long available, long total, long free)
     {
      this.Drive = drive;
      this.Result = result;
      this.Available = available;
      this.Total = total;
      this.Free = free;
     }
    }
    and then you can use it as :
    然后你也可以使用下面这种方法:
    DriveInfoSystem info = DriveInfo.GetInfo("c:");
  • 相关阅读:
    Java 中String、StringBuffer、StringBuilder的差别
    [转载]StringBuffer versus String
    二维数组的连续子数组的最大和
    一位数组的最大和
    js中常见的去重方式
    魅族2016Java互联网方向其中一道笔试题--青蛙跳台阶问题
    美团在线编程2016--最大差值
    [转载]MySQL开发中常用的查询语句总结
    实现字符串全排列
    笔试题---最大子序列和
  • 原文地址:https://www.cnblogs.com/zjp8023/p/CodeProject01.html
Copyright © 2020-2023  润新知