~relax~
這是一個悠閒放鬆的部落格,請用輕鬆的心情閱讀文章,在忙碌工作之餘療癒自己的身心。 (最近發現我的文章被複製轉貼且沒有註明出處,本部落格的文章皆為原創,若有引用參考也會註明,如有需求請留言告知,謝謝!)

目前分類:C#/VB/ASP.NET (46)

瀏覽方式: 標題列表 簡短摘要
using System.Runtime.InteropServices;

[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int LCMapString(int locale, int dwMapFlags, string lpSrcStr, int cchSrc,
                                                                          [Out] string lpDestStr, int cchDest);

public static string ToSimplified(string argSource)
{
        var t = new String(' ', argSource.Length);
        LCMapString(LocaleSystemDefault, LcmapSimplifiedChinese, argSource, argSource.Length, t, argSource.Length);
        return t;
}

public static string ToTraditional(string argSource)
{
        var t = new String(' ', argSource.Length);
        LCMapString(LocaleSystemDefault, LcmapTraditionalChinese, argSource, argSource.Length, t, argSource.Length);
        return t;
}

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue); //Create new Excel
Excel.Worksheet xlWorkSheet= (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); //取第一個Sheet

//指定列高, Object的高度約55像素, 這裡用第3列為範例
((Excel.Range)xlWorkSheet.Rows["3:3", System.Type.Missing]).RowHeight = 55;

//取得位置, 這裡用H3為範例
Excel.Range ColH = xlWorkSheet.get_Range("H3");

//Add OLE Object
xlWorkSheet.Shapes.AddOLEObject(ClassType: Type.Missing
        , Filename: Directory.GetCurrentDirectory() + "\\PDF檔案名稱.pdf"
        , Link: false
        , DisplayAsIcon: true
        , IconFileName: Directory.GetCurrentDirectory() + "\\PDF的Icon檔案名稱.ico"
        , IconIndex: "0"
        , IconLabel: "這裡可以寫字"
        , Left: ColH.Left //放 OLE Object 的位置
        , Top: ColH.Top //放 OLE Object 的位置
        //, Width: 15 //有設定Icon時, Width/Height的設定貌似無效
        //, Height: 15 //有設定Icon時, Width/Height的設定貌似無效
);

//xlWorkSheet.Cells.EntireRow.AutoFit(); //自動列高, 因為有指定列高, 這邊不設定自動
xlWorkSheet.Cells.EntireColumn.AutoFit(); //自動欄寬

//另存新檔
xlWorkBook.SaveAs(@"存檔路徑 \\172.16.0.11\Report\", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

//關閉
xlWorkBook.Close(true, misValue, misValue);
xlApp.DisplayAlerts = false;
xlApp.Quit();

//釋放
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);


private void releaseObject(object obj)
{
        try
        {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
        }
        catch (Exception ex)
        {
                obj = null;
                Console.WriteLine("Unable to release the Object " + ex.ToString());
        }
        finally
        {
                GC.Collect();
        }
}

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

Xml File 內容 :

<?xml version="1.0" standalone="yes"?>
<table1>
    <Name>Alice</Name>
    <Mail>alice@mail.com</Mail>

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

功能說明 : 避免程式被不小心關閉(按右上角的[X]會縮小, 不會關閉), 不要佔用下方工具列, 縮小到系統匣, 縮小時右下角出現提示訊息.

其他功能說明 : 複製指定檔案, 指定來源及目的路徑, 會遞迴往下尋找資料夾, 目的路徑自動複製來源資料夾的結構.

 

config : 指定檔案, 指定來源及目的路徑.

config1.png

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

參考:http://no2don.blogspot.com/2013/02/c-nopi-excel-xls.html

下載NPOI的dll,放到專案 (共五個dll)

using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;

//建立 Workbook
XSSFWorkbook wb = new XSSFWorkbook();

//建立一個叫做"Sheet1"的 Sheet
XSSFSheet st = (XSSFSheet)wb.CreateSheet("Sheet1");

//生成一個新Row (第一列:0, 第二列:1, ...類推)
int row_index = 0;
st.CreateRow(row_index);
//生成這個Row的Cell, 且放值進去 (第一格:0, 第二格:1, ...類推)
st.GetRow(row_index).CreateCell(0, CellType.String).SetCellValue("內容值"); //A1
st.GetRow(row_index).CreateCell(1, CellType.String).SetCellValue("內容值"); //B1

//再生成一個新Row
st.CreateRow(++row_index);
//生成這個Row的Cell, 且放值進去
st.GetRow(row_index).CreateCell(0, CellType.String).SetCellValue("內容值"); //A2
st.GetRow(row_index).CreateCell(1, CellType.String).SetCellValue("內容值"); //B2

//寫入
var file = new FileStream("檔案路徑\\檔案名稱.xlsx", FileMode.Create);
wb.Write(file);
file.Close();

//關閉 Workbook
wb = null;

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

//設定連線參數
RfcConfigParameters parms = new RfcConfigParameters();

parms.Add(RfcConfigParameters.AppServerHost, ServerIP); //172.16.0.1
parms.Add(RfcConfigParameters.SystemNumber, SystemNumber); //00
parms.Add(RfcConfigParameters.SystemID, SystemID); //PRD
parms.Add(RfcConfigParameters.User, User); //SAPUSER
parms.Add(RfcConfigParameters.Password, Password); //SAPPWD
parms.Add(RfcConfigParameters.Client, Client); //225
parms.Add(RfcConfigParameters.Language, "EN");
parms.Add(RfcConfigParameters.PoolSize, "5");
parms.Add(RfcConfigParameters.PeakConnectionsLimit, "10");
parms.Add(RfcConfigParameters.ConnectionIdleTimeout, "600");
parms.Add(RfcConfigParameters.Name, "LIPS");


//取得連線
RfcDestination destination = RfcDestinationManager.GetDestination(parms);

RfcSessionManager.BeginContext(destination);

destination.Ping();


//宣告RfcFunction
IRfcFunction rfcFunction = destination.Repository.CreateFunction(RfcFunctionName);

//設定RfcFunction Table參數
rfcFunction.SetValue("AUFNR", 傳入參數); //傳入型別: 字串(string), 代表意義 工單
rfcFunction.SetValue("LOC_TYPE", 傳入參數); //傳入型別: 字元(character), 代表意義 R:電阻 C:電容 L:電感

//執行此RfcFunction以產生RfcFunction Table
rfcFunction.Invoke(destination);


//取回RfcFunction產生的Table
IRfcTable table = rfcFunction.GetTable(TableName);

//destination = null;//關閉連線
if (destination != null)
{
    RfcSessionManager.EndContext(destination);
    destination = null;
}

DataTable dt = new DataTable();  //新建表格
dt.Columns.Add("Part");  //表格添加一列
dt.Columns.Add("Location");  //表格添加一列
for (int i = 0; i < table.RowCount; i++)
{
    table.CurrentIndex = i;  //当前内表的索引行

    string PartName = string.Empty;
    string Location = string.Empty;

    PartName = table.GetString("MATNR");  //获取表格的某行某列的值
    Location += table.GetString("LOC1");
    Location += table.GetString("LOC2");
    Location += table.GetString("LOC3");

    //Console.WriteLine(PartName);
    //Console.WriteLine(Location);

    //開始Parser資訊...
}

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

ASP.NET (Web Page) 網頁 是不能使用建立網路磁碟機連線功能的

但是可以支援UNC路徑,可存取網路上分享的資料夾

路徑格式:\\IP Address or 電腦名稱\資料夾名稱\檔案名稱

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

//宣告
List<string> Items = new List<string>();

//塞值
Items.Add("ABC");
Items.Add("DEF");
Items.Add("GIH");

//傳給另一個變數
List<string> ItemsBackup = new List<string>();
ItemsBackup = Items.ToArray();

//自訂List
public class myListItem
{
    public string Name { get; set; }
    public int Age { get; set; }       
}
//宣告
List<myListItem> Items = new List<myListItem>();
//塞值
Items.Add(new myListItem()
{
        Name = "Annie",
        Age = 18,
});

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

用C#示範

void Timer1Tick(object sender, EventArgs e)
{
        string str = txtPrintBuffer.Text; //取出欲顯示的字串,string做處理比較方便
        txtPrint.Text = txtPrint.Text + str[txtPrint.TextLength]; //逐字顯示
        
        //以下三行是讓TextBox自動捲到最下面
        txtPrint.SelectionStart = txtPrint.Text.Length;*
        txtPrint.ScrollToCaret(); 
        txtPrint.Refresh();
        
        //如果已經顯示字串最尾,就停止Timer
        if(txtPrint.TextLength == str.Length) timer1.Enabled = false;
}

void StringDelayPrint(string str)
{
        if(timer1.Enabled == true) return; //如果已經在顯示中,不要繼續重複動作
        txtPrint.Text = ""; //清除顯示用的TextBox
        txtPrintBuffer.Text = str; //將要顯示的字串存到暫存TextBox中
        timer1.Interval = 300; //設定每字顯示的間隔時間,毫秒為單位
        timer1.Enabled = true; //將Timer元件啟動
}

void Button1Click(object sender, EventArgs e)
{
        //用東方神起的中文版歌詞當示範,剛好寫程式時在聽 ...
        //剛好也可以示範一下字串在程式碼中如何斷行 ...
        //還有換行符號 ...
        string str = 
                "一次 一次也沒有 直到最後也沒有對我敞開心扉\r\n" + 
                "我就想面壁而立的心情 你知道嗎\r\n" + 
                "\r\n" + 
                "雖然在身邊卻變得更加孤獨\r\n" + 
                "tonight tonight tonight\r\n" + 
                "\r\n" + 
                "雖然等待了你 但不會這樣了\r\n" + 
                "現在我要離開你\r\n" + 
                "\r\n" + 
                "不要走 我一句都不會說 你這個傻瓜\r\n" + 
                "我為什麼只看著你這個傻瓜 那麼不爭氣的你\r\n" + 
                "\r\n" + 
                "baby catch me catch me catch me girl tonight\r\n" + 
                "在我離開你之前(I'm serious I'm serious)\r\n" + 
                "\r\n" + 
                "抓著我不讓走 哭著打我 如果告訴我理由\r\n" + 
                "(I'm serious I'm serious)\r\n" + 
                "\r\n";
        
        StringDelayPrint(str);
}

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

這裡是範例程式碼,想知道原理的請閱讀:[三菱PLC] 學習筆記 指令 及 透過RS232(USB介面)監控 PLC

    public partial class MainForm : Form
    {
        System.IO.Ports.SerialPort serialport = new System.IO.Ports.SerialPort();//宣告連接埠
        Boolean light = false, serialportopen = false;
        
        public MainForm()
        {
            InitializeComponent();
            
            foreach(string com in System.IO.Ports.SerialPort.GetPortNames())//取得所有可用的連接埠
            {
                cbPortName.Items.Add(com);
            }
            if (cbPortName.Items.Count > 0)
                cbPortName.SelectedIndex = 0;
            
            cbCmd.Items.Add("0-讀取");
            cbCmd.Items.Add("1-寫入");
            cbCmd.Items.Add("7-強制ON");
            cbCmd.Items.Add("8-強制OFF");
            if(cbCmd.Items.Count>1)
                cbCmd.SelectedIndex=0;
        }
        
        void Button1Click(object sender, EventArgs e)
        {
            if (serialportopen == false && !serialport.IsOpen)
            {
                try
                {
                    //設定連接埠
                    serialport.PortName = cbPortName.Text;//連線埠
                    serialport.BaudRate = 9600;//鮑率
                    serialport.DataBits = 7;//數據位元
                    serialport.Parity = System.IO.Ports.Parity.Even;//偶同位
                    serialport.StopBits = System.IO.Ports.StopBits.One;//停止位元
                    serialport.Encoding = Encoding.Default;//傳輸編碼方式
                    serialport.Open();
                    serialportopen = true;
                    button2.Enabled = true;
                    txtSTX.Enabled = true;
                    if (this.backgroundWorker1.IsBusy != true)
                    {
                        this.backgroundWorker1.WorkerReportsProgress = true;
                        this.backgroundWorker1.RunWorkerAsync();
                    }
                    button1.Text = "中斷";
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            else if (serialportopen == true && serialport.IsOpen)
            {
                try
                {
                    serialport.Close();
                    if (!serialport.IsOpen)
                    {
                        serialportopen = false;
                        button2.Enabled = false;
                        txtSTX.Enabled = false;
                        this.backgroundWorker1.WorkerReportsProgress = false;
                        this.backgroundWorker1.CancelAsync();
                        this.backgroundWorker1.Dispose();
                        label3.ForeColor = Color.Red;
                        button1.Text = "連線";
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        

        private void Button2Click(object sender, EventArgs e)
        {
            try
            {
                string str = "";
                //STX Cmd Addrs Bytes Data ETX SUM
                //str = (Char)2 + "70008" + (Char)3 + "02";//M0
                //str = (Char)2 + "70108" + (Char)3 + "03";//M1
                //str = (Char)2 + "70208" + (Char)3 + "04";//M2
                //str = (Char)2 + "70308" + (Char)3 + "05";//M3
                str = (Char)2 + txtCmd.Text + txtAddrs.Text + txtBytes.Text + txtData.Text + (Char)3 + txtSum.Text;
                serialport.Write(str);
                AddText(MsgType.Error, "傳送:" + str + "\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar==(Char)13)
            {
                Button2Click(sender, e);
            }
        }

        private void BackgroundWorker1DoWork(object sender, DoWorkEventArgs e)
        {
            for (; ; )
            {
                if (backgroundWorker1.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    try
                    {
                        backgroundWorker1.ReportProgress(0);
                        System.Threading.Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {
                        e.Cancel = true;
                        break;
                    }
                }
            }
        }

        private void BackgroundWorker1ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {
                if (serialport.BytesToRead != 0)
                {
                    label2.Text = "緩衝區:" + serialport.BytesToRead.ToString();
                    AddText(MsgType.System, "接收:" + serialport.ReadExisting() + "\r\n");
                    serialport.DiscardInBuffer();
                }
            }
            catch(Exception)
            {}
        }

        private void AddText(MsgType msgtype, string msg)
        {
            richTextBox1.Invoke(new EventHandler(delegate
            {
                richTextBox1.SelectedText = string.Empty;
                richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
                richTextBox1.SelectionColor = MsgTypeColor[(int)msgtype];
                richTextBox1.AppendText(msg);
                richTextBox1.ScrollToCaret();
            }));
        }
        
        //FX2N CheckSum,取 CMD、ADDR、DATA、ETX 各字元的 ASCII碼 16進位表示法 加總,然後取最後兩個字元。
        private string CheckSum()
        {
            //宣告:int為整數、string為字符串
            int sum = 0;
            string checkstring = "";
            string checksum = "";
        
            //通訊格式中的英文字符必須為大寫(a~f),故先行將text所輸入之傳送數據,經由程序自動轉換為大寫字母,然後加上結束碼etx:chr(3),形成一字符串checkstring
            checkstring = (String)txtCmd.Text + txtAddrs.Text + txtBytes.Text + txtData.Text + (Char)3;
        
            // for屬於重複結構中之計數循環,指令pc在一定的次數內,重複的執行某一敘述區段,亦即取出checkstring字符串中每一個字符,並累加每一個字符的ascii碼,而得出一整數sum。
            for (int i = 0; i < checkstring.Length; i++) {
                sum = sum + Convert.ToInt32(checkstring[i]);
            }
        
            //將10進制整數sum轉換為16進制,並取其右邊二位數,即為所求檢查碼。
            checksum = String.Format("{0:X}", sum);
            checksum.PadLeft(2,'0');
            checksum = checksum.Substring(checksum.Length - 2, 2);
            
            return checksum;
        }
        
        void Button3Click(object sender, EventArgs e)
        {
            string sum = CheckSum();
            txtSum.Text = sum;
        }
        
        void CbCmdSelectedIndexChanged(object sender, EventArgs e)
        {
            string cmd = cbCmd.Text.Split('-')[0];
            txtCmd.Text = cmd;
        }
        
        void SendStr(string str)
        {
            try
            {
                //STX Cmd Addrs Bytes Data ETX SUM
                //str = (Char)2 + "70008" + (Char)3 + "02";//M0
                //str = (Char)2 + "70108" + (Char)3 + "03";//M1
                //str = (Char)2 + "70208" + (Char)3 + "04";//M2
                //str = (Char)2 + "70308" + (Char)3 + "05";//M3
                serialport.Write(str);
                AddText(MsgType.Error, "傳送:" + str + "\r\n");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }

文章標籤

伊 發表在 痞客邦 留言(2) 人氣()

延伸閱讀:[三菱PLC][使用C#] 透過RS232(USB介面)監控PLC 範例程式碼

【通訊】

RS232(PC) 對 RS422(PLC)

文章標籤

伊 發表在 痞客邦 留言(2) 人氣()

這個範例程式,會顯示進度字串到textbox內,textbox會自動捲動到最下方,會顯示進度條(0~100),可讓使用者中斷程序。
VB部分的程式碼我是用網路上C#toVB轉換器轉的,所以不知道有無錯誤,請網友費心試試看囉~

程式元件畫面:
NET背景執行

文章標籤

伊 發表在 痞客邦 留言(6) 人氣()

//C#

//開啟檔案
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.CheckFileExists = true;
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt";
OpenFileDialog1.Multiselect = false;
OpenFileDialog1.ShowDialog();
TextBox.Text = OpenFileDialog1.FileName;

//開啟資料夾
FolderBrowserDialog FolderBrowserDialog1= new FolderBrowserDialog();
FolderBrowserDialog1.ShowDialog();
TextBox.Text = FolderBrowserDialog1.SelectedPath;
'VB

'開啟檔案
Dim OpenFileDialog1 As OpenFileDialog = New OpenFileDialog
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt"
OpenFileDialog1.Multiselect = False
OpenFileDialog1.ShowDialog()
TextBox.Text = OpenFileDialog1.FileName

'開啟資料夾
Dim FolderBrowserDialog1 As FolderBrowserDialog = New FolderBrowserDialog
FolderBrowserDialog1.ShowDialog()
TextBox.Text = FolderBrowserDialog1.SelectedPath

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#

//檢查檔案是否存在
if (!File.Exists(FilePath))
{
    MessageBox.Show("找不到檔案");
    return;
}

StreamReader objReader = new StreamReader(FilePath);
string sLine = "";
ArrayList arrText = new ArrayList();

do
{
    sLine = objReader.ReadLine();
    if (sLine != null)
    {
        arrText.Add(sLine);
    }
} while (sLine != null);
objReader.Close();

//把讀取檔案的結果放到ListBox,您也可以另做運用。
ListBox.Items.AddRange(arrText);

VB

'檢查檔案是否存在
If Not FileIO.FileSystem.FileExists(FilePath) Then
    MsgBox("找不到檔案")
    Return
End If

Dim objReader As New StreamReader(FilePath)
Dim sLine As String = ""
Dim arrText As New ArrayList()

Do
    sLine = objReader.ReadLine()
    If Not sLine Is Nothing Then
        arrText.Add(sLine)
    End If
Loop Until sLine Is Nothing
objReader.Close()

'把讀取檔案的結果放到ListBox,您也可以另做運用。
ListBox.Items.AddRange(arrText)

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#
int 這個月的天數 = DateTime.DaysInMonth(年,月);

VB
Dim 這個月的天數 As Integer = DateTime.DaysInMonth(年,月)

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#

//檔案是否存在
bool result = System.IO.File.Exists(檔案路徑);

//資料夾是否存在
bool result = System.IO.Directory.Exists(資料夾路徑);

//建立資料夾
System.IO.Directory.CreateDirectory(資料夾路徑);

//檢查是否為合法路徑
public bool isValidPath(string path)
{
    bool result = true;
    string err = "";
    try
    {
        System.IO.FileInfo info = new System.IO.FileInfo(path);
    }
    catch (Exception ex)
    {
        result = false;
        err = "err:" + ex.Message;
    }
    Console.WriteLine("{0} {1} {2}", result, path, err);
    return result;
}

//取得資料夾資訊
DirectoryInfo dir = new DirectoryInfo(資料夾路徑);

//搜尋資料夾1
DirectoryInfo[] dirList = dir.GetDirectories(搜尋字串, SearchOption);
//搜尋資料夾2
string[] dirList = Directory.GetDirectories(資料夾路徑, 搜尋字串, SearchOption);

//搜尋檔案1
FileInfo[] fileList = dir.GetFiles(搜尋字串, SearchOption);
//搜尋檔案2
string[] fileList = Directory.GetFiles(資料夾路徑, 搜尋字串, SearchOption);

//巡覽DirectoryInfo
foreach (DirectoryInfo _event in dirList)
{
    //...
}

//巡覽FileInfo
foreach (FileInfo _event in fileList)
{
    //...
}

//取得目前使用者桌面路徑
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath =desktopPath +@"\FolderTest\";
//檢查資料夾是否存在
if (!Directory.Exists(filePath))
{
    //不存在則建立
    Directory.CreateDirectory(filePath);
}
//檢查檔案是否存在
if (!File.Exists(filePath))
{
    //不存在則拷貝
    File.Copy(來源路徑含檔名, 目的路徑含檔名, true);
}

VB

'檔案是否存在
FileIO.FileSystem.FileExists(檔案路徑)

'資料夾是否存在
FileIO.FileSystem.DirectoryExists(資料夾路徑)

'建立資料夾
FileIO.FileSystem.CreateDirectory(資料夾路徑)

'檢查是否為合法路徑
Public Function isValidPath(ByVal path As String) As Boolean
    Dim result As Boolean = True
    Dim err As String = ""
    Try
        Dim info As New System.IO.FileInfo(path)
    Catch ex As Exception
        result = False
        err = "err:" & ex.Message
    End Try
    Console.WriteLine("{0} {1} {2}", result, path, err)
    Return result
End Function

'取得資料夾資訊
Dim dir As New DirectoryInfo(資料夾路徑)

'搜尋資料夾1
Dim dirList As DirectoryInfo() = dir.GetDirectories(搜尋字串, SearchOption)
'搜尋資料夾2
Dim dirList As String() = Directory.GetDirectories(資料夾路徑, 搜尋字串, SearchOption)

'搜尋檔案1
Dim fileList As FileInfo() = dir.GetFiles(搜尋字串, SearchOption)
'搜尋檔案2
Dim fileList As String() = Directory.GetFiles(資料夾路徑, 搜尋字串, SearchOption)

'巡覽DirectoryInfo
For Each _event As DirectoryInfo In dirList
        '...
Next

'巡覽FileInfo
For Each _event As FileInfo In fileList
        '...
Next

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#

textbox1.SelectionStart = textbox1.Text.Length; 
textbox1.ScrollToCaret(); 
textbox1.Refresh();

VB

textbox1.SelectionStart = textbox1.Text.Length
textbox1.ScrollToCaret()
textbox1.Refresh()

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#

[DllImport("mpr.dll", EntryPoint = "WNetAddConnectionA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern long WNetAddConnection(string lpszNetPath, string lpszPassword, string lpszLocalName);

[DllImport("mpr.dll", EntryPoint = "WNetCancelConnectionA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
public static extern long WNetCancelConnection(string lpszName, long bForce);

//無密碼可傳空字串
public long AddConnection(string 路徑, string 登入密碼, string 磁碟機代號)
{
    try
    {
        return WNetAddConnection(路徑, 登入密碼, 磁碟機代號);
    }
    catch (Exception ex)
    {
        DebugMsg(ex.Message.ToString());
        return 0;
    }
}

//Force: 0 如有檔案開啟中則傳回ERROR_OPEN_FILES, 1 強制關閉
//ERROR_OPEN_FILES: There are open files, and the fForce parameter is FALSE.
public long CancelConnection(string 磁碟機代號, int Force)
{
    try
    {
        return WNetCancelConnection(磁碟機代號, Force);
    }
    catch (Exception ex)
    {
        DebugMsg(ex.Message.ToString());
        return 0;
    }
}

VB

Declare Function WNetAddConnection Lib "mpr.dll" Alias "WNetAddConnectionA" _
(ByVal lpszNetPath As String, ByVal lpszPassword As String, ByVal lpszLocalName _
As String) As Long

Declare Function WNetCancelConnection Lib "mpr.dll" Alias "WNetCancelConnectionA" _
(ByVal lpszName As String, ByVal bForce As Long) As Long

Function AddConnection(ByVal 路徑 As String, ByVal 登入密碼 As String, ByVal 磁碟機代號 As String) As Long
    Try
        Return WNetAddConnection(路徑, 登入密碼, 磁碟機代號)
    Catch ex As Exception
        DebugMsg(ex.Message.ToString())
    End Try
End Function

Function CancelConnection(ByVal 磁碟機代號 As String, ByVal Force As Integer) As Long
    Try
        Return WNetCancelConnection(磁碟機代號, Force)
    Catch ex As Exception
        DebugMsg(ex.Message.ToString())
    End Try
End Function

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

C#

//宣告: 型別[] 變數名稱 = { 陣列內容1, 陣列內容2, 陣列內容3, 陣列內容4 ... };
string[] LocalNameList = { "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V" };

//巡覽1 foreach
foreach (string _event in LocalNameList)
{
    textbox1.text = _event;
}

//巡覽2 for
for (i = 0; i < LocalNameList.Length; i++)
{
    textbox1.text = LocalNameList[i];
}

//排序   使用Array.Sort ( , )    
//範例: 
//依檔名排序 = _event.Name;
//or 
//依檔案最後修改的日期時間 = _event.LastWriteTime.ToString()
private FileInfo[] SortFiles(FileInfo[] files)
{
    int array_length = files.Length;
    string[] sort_key = new string[array_length];

    foreach (FileInfo _event in files)
    {
        sort_key[0] = _event.Name; //依檔名
        //sort_key[0] = _event.LastWriteTime.ToString(); //依檔案最後修改的日期時間
    }

    Array.Sort(sort_key, files); //由小到大排序
    Array.Reverse(files); //反轉 由大到小排序

    return files;
}

//陣列Function的宣告
//類型 型別[] 名稱(參數...) 
private FileInfo[] SortFiles(FileInfo[] files)
{
    return files;
}

VB

'宣告: Dim 變數名稱() As 型別 = { 陣列內容1, 陣列內容2, 陣列內容3, 陣列內容4 ... }
Dim LocalNameList() As String = {"G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V"}

'巡覽1 For Each
For Each _event As String In LocalNameList
    textbox1.text = _event 
Next

'巡覽2 For
For i = 0 To LocalNameList.Length - 1
    textbox1.text = LocalNameList(i)
Next

'排序   使用Array.Sort ( , )    
'範例: 
'依檔名排序 = _event.Name;
'or 
'依檔案最後修改的日期時間 = _event.LastWriteTime.ToString()
Private Function SortFiles(ByVal files As FileInfo()) As FileInfo()
    Dim array_length As Integer = files.GetUpperBound(0)
    Dim sort_key(array_length) As String

    For Each dir As FileInfo In files
        sort_key(0) = dir.Name '依檔名
        'sort_key(0) = dir.LastWriteTime.ToString '依檔案最後修改的日期時間
    Next

    Array.Sort(sort_key, files) '由小到大排序
    Array.Reverse(files) '反轉 由大到小排序

    Return files
End Function

'陣列Function的宣告
'類型 Function 名稱(參數...) As 型別() 
Private Function SortFiles(ByVal files As FileInfo()) As FileInfo()
    Return files
End Function

文章標籤

伊 發表在 痞客邦 留言(0) 人氣()

很有參考價值,微軟官網:
http://msdn.microsoft.com/zh-tw/library/dayb112d.aspx


伊 發表在 痞客邦 留言(0) 人氣()

1 23