茫茫網海中的冷日
         
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已!
 恭喜您是本站第 1672011 位訪客!  登入  | 註冊
主選單

Google 自訂搜尋

Goole 廣告

隨機相片
IMG_60D_00037.jpg

授權條款

使用者登入
使用者名稱:

密碼:


忘了密碼?

現在就註冊!

Dot Net? : [轉貼]C# 讀寫 txt 檔的兩種方法介紹

發表者 討論內容
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]C# 讀寫 txt 檔的兩種方法介紹

C#讀寫txt檔的兩種方法介紹

1.添加命名空間

 

System.IO;

 

System.Text;

 

2.檔的讀取

 

(1).使用FileStream類進行檔的讀取,並將它轉換成char陣列,然後輸出。

 

01.byte[] byData = new byte[100];
02. char[] charData = new char[1000];
03. public void Read()
04. {
05. try
06. {
07. FileStream file = new FileStream("E:\\test.txt", FileMode.Open);
08. file. Seek(0, SeekOrigin.Begin);
09. file. Read(byData, 0, 100); //byData傳進來的位元組陣列,用以接受FileStream物件中的資料,第2個參數是位元組陣列中開始寫入資料的位置,它通常是0,表示從陣列的開端檔中向陣列寫資料,最後一個參數規定從檔讀多少字元.
10. Decoder d = Encoding.Default.GetDecoder();
11. d.GetChars(byData, 0, byData.Length, charData, 0);
12. Console.WriteLine(charData);
13. file. Close();
14. }
15. catch (IOException e)
16. {
17. Console.WriteLine(e.ToString());
18. }
19. }



(2).使用StreamReader讀取檔,然後一行一行的輸出。

 

01.public void Read(string path)
02. {
03. StreamReader sr = new StreamReader(path,Encoding.Default);
04. String line;
05. while ((line = sr. ReadLine()) != null)
06. {
07. Console.WriteLine(line. ToString());
08. }
09. }



3.檔的寫入
(1).使用FileStream類創建檔,然後將資料寫入到檔裡。

 

01.public void Write()
02. {
03. FileStream fs = new FileStream("E:\\ak.txt", FileMode.Create);
04. //獲得位元組陣列
05. byte[] data = System.Text.Encoding.Default.GetBytes("Hello World!");
06. //開始寫入
07. fs. Write(data, 0, data. Length);
08. //清空緩衝區、關閉流
09. fs. Flush();
10. fs. Close();
11. }



(2).使用FileStream類創建檔,使用StreamWriter類,將資料寫入到檔。

 

01.public void Write(string path)
02. {
03. FileStream fs = new FileStream(path, FileMode.Create);

04. StreamWriter sw = new StreamWriter(fs);
05. //開始寫入
06. sw. Write("Hello World!!!!");
07. //清空緩衝區
08. sw. Flush();
09. //關閉流
10. sw. Close();
11. fs. Close();
12. }



以上就完成了,txt文字文件的資料讀取與寫入。

shadow 發表在 痞客邦 PIXNET 留言(0)
引用(0)


原文出處:C#讀寫txt檔的兩種方法介紹 @ 資訊園 :: 痞客邦 PIXNET ::
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]如何:寫入文字檔 (C# 程式設計手冊)
如何:寫入文字檔 (C# 程式設計手冊)
Visual Studio 2013

在下列這些範例中,會示範幾個將文字寫入檔案的方法。 前兩個範例會在 System.IO.File 類別上使用靜態方法,將完整字串陣列或完整字串寫入文字檔。 範例 3 中會示範如何在需要分別處理每一行時,先將文字加入至檔案,然後再寫入檔案。 範例 1 到 3 會覆寫檔案中的全部現有內容。 範例 4 中會示範如何將文字附加至現有的檔案。
範例
C#
class WriteTextFile
{
    static void Main()
    {

        // These examples assume a "C:\Users\Public\TestFolder" folder on your machine.
        // You can modify the path if necessary.

        // Example #1: Write an array of strings to a file.
        // Create a string array that consists of three lines.
        string[] lines = { "First line", "Second line", "Third line" };
        // WriteAllLines creates a file, writes a collection of strings to the file,
        // and then closes the file.
        System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);


        // Example #2: Write one string to a text file.
        string text = "A class is the most powerful data type in C#. Like a structure, " +
                       "a class defines the data and behavior of the data type. ";
        // WriteAllText creates a file, writes the specified string to the file,
        // and then closes the file.
        System.IO.File.WriteAllText(@"C:\Users\Public\TestFolder\WriteText.txt", text);

        // Example #3: Write only some strings in an array to a file.
        // The using statement automatically closes the stream and calls
        // IDisposable.Dispose on the stream object.
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt"))
        {
            foreach (string line in lines)
            {
                // If the line doesn't contain the word 'Second', write the line to the file.
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
        }

        // Example #4: Append new text to an existing file.
        // The using statement automatically closes the stream and calls
        // IDisposable.Dispose on the stream object.
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\Public\TestFolder\WriteLines2.txt", true))
        {
            file.WriteLine("Fourth line");
        }
    }
}
 //Output (to WriteLines.txt):
 //   First line
 //   Second line
 //   Third line

 //Output (to WriteText.txt):
 //   A class is the most powerful data type in C#. Like a structure, a class defines the data and behavior of the data type.

 //Output to WriteLines2.txt after Example #3:
 //   First line
 //   Third line

 //Output to WriteLines2.txt after Example #4:
 //   First line
 //   Third line
 //   Fourth line


這些範例全都會將字串常值寫入至檔案,不過您可能比較想要使用 Format 方法,該方法提供許多控制項讓您撰寫不同類型的值,在欄位中靠右或靠左對齊、使用或不使用邊框間距等等。
編譯程式碼

將程式碼複製至主控台應用程式。

以您電腦上的實際資料夾名稱來取代 "c:\testdir",或以那個名稱來建立資料夾。
穩固程式設計

以下條件可能會造成例外狀況:

該檔案存在而且是唯讀的。

路徑名稱可能太長。

磁碟可能已滿。

請參閱
概念
C# 程式設計手冊
其他資源
檔案系統和登錄 (C# 程式設計手冊)
如何將自訂物件集合儲存至本機存放區

原文出處:如何:寫入文字檔 (C# 程式設計手冊)
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]如何:將文字寫入檔案
如何:將文字寫入檔案
.NET Framework 4.5

下列範例將示範如何將文字寫入文字檔。
範例

第一個範例藉由搜尋會從使用者的我的文件資料夾中的所有文字檔 "*.txt"同步處理並將其寫入大型文字檔。
C#
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        StringBuilder sb = new StringBuilder();

        foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
        {
            using (StreamReader sr = new StreamReader(txtName))
            {
                sb.AppendLine(txtName.ToString());
                sb.AppendLine("= = = = = =");
                sb.Append(sr.ReadToEnd());
                sb.AppendLine();
                sb.AppendLine();
            }
        }

        using (StreamWriter outfile = new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
        {
            outfile.Write(sb.ToString());
        }
    }
}


下一個範例顯示如何以非同步方式從文字方塊中寫入使用者的輸入至檔案。
C#
using System;
using System.Text;
using System.Windows;
using System.IO;

namespace WpfApplication
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void AppendButton_Click(object sender, RoutedEventArgs e)
        {
            string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("New User Input");
            sb.AppendLine("= = = = = =");
            sb.Append(UserInputTextBox.Text);
            sb.AppendLine();
            sb.AppendLine();

            using (StreamWriter outfile = new StreamWriter(mydocpath + @"\UserInputFile.txt", true))
            {
                await outfile.WriteAsync(sb.ToString());
            }
        }
    }
}


請參閱
工作
如何:列舉目錄和檔案
如何:讀取和寫入新建立的資料檔案
如何:開啟並附加至記錄檔
如何:從檔案讀取文字
如何:從字串中讀取字元
如何:將字元寫入至字串
參考
StreamWriter
File.CreateText
其他資源
檔案和資料流 I/O

原文出處:如何:將文字寫入檔案
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼]C# 檔案讀寫

2010 04 01 22 06 [C#] 檔案讀寫

From: Head First C# [Chapter 9] Reading and writing files

  檔案讀寫是程式設計師很常遇到的問題,在 C# 中與 Java 相同,不管是檔案讀寫、網路資料傳送、螢幕鍵盤輸出入都是以「串流(Stream)」的方式來達成。FileStream、MemoryStream、NetworkStream、GZipStream 等都繼承自 Stream 類別。在這個章節裡我們直接以範例來學習。

一、文字讀寫

1. 將文字寫入 C:\secret_plan.txt 中。


// 建立檔案串流(@ 可取消跳脫字元 escape sequence)
StreamWriter sw = new StreamWriter(@"C:\secret_plan.txt");
sw.WriteLine("write something"); // 寫入文字
sw.Close(); // 關閉串流

2. 讀取文字


// 建立檔案串流(@ 可取消跳脫字元 escape sequence)
StreamReader sr = new StreamReader(@"C:\secret_plan.txt");
while (!sr.EndOfStream) { // 每次讀取一行,直到檔尾
string line = sr.ReadLine(); // 讀取文字到 line 變數
}
sr.Close(); // 關閉串流

Stream 類別實作了 IDisposable 介面!它具有 Dispose 方法,你可以呼叫 Dispose 關閉串流或者使用 using statement。

using (StreamWriter sw = new StreamWriter(@"C:\secret_plan.txt")) {
...
}

  看到這裡是不是覺得太簡單了呢!等等呢,Visual C# 有一個 OpenFileDialog 的對話框可以用來選取檔案。下面就來看看怎麼使用吧!

Step1:將 OpenFileDialog 控制項拖曳到表單上

拖曳新增後 OpenFileDialog 控制項會出現在 Form Design 下方。在此我們假定該控制項命名 openFileDialog1 。

Step2:撰寫控制碼

在 Form 底下撰寫 OpenFileDialog 的控制碼。


openFileDialog1.InitialDirectory = @"c:\MyFolder\Default\";	// 檔案對話方框開啟的預設資料夾
// 設定可以選擇的檔案類型
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|Comma-Delimited Files (*.csv)|*.csv|All Files (*.*)|*.*";
openFIleDialog1.CheckFileExists = true; // 若檔案/路徑 不存在是否顯示錯誤訊息
openFIleDialog1.CheckPathExists = false;
DialogResult result = openFileDialog1.ShowDialog(); // 顯示檔案對話方框並回傳狀態(DialogResult.OK、DialogResult.Cancel)
if (result == DialogResult.OK) {
// 操作檔案 openFileDialog1.FileName
}

除了 OpenFileDialog 外,SaveFileDialog 的作法也是一樣的。

二、File 類別 - 更快的方法來處理簡單的檔案管理


bool b = File.Exists(file_name);		// 判定檔案是否存在
File.Create(file_name); // 建立檔案
string text = File.ReadAllText(file_name); // 讀取檔案內所有文字
File.WriteAllText(file_name, text); // 將 text 寫入檔案

* File 類別還有很多方法,詳細參考 Head First C#、其他書籍或 MSDN

三、物件序列化(serialization)

  物件序列化是一個快速又方便的物件狀態永久保存法,它將物件的狀態(所有成員變數)儲存到檔案中。以下範例展示序列化(serialize)與反序列化(deserialize)。


[Serializable]				// *這一行很重要
class AnotherObj {}
class SomeObj {
public int x; // 該變數會被保存
public AnotherObj another; // 該物件也會被保存,但其類別需加上 [Serializable] 屬性(attribute)
}

Step1:引入 namespace

在 .cs 檔前頭加上 using System.Runtime.Serialization.Formatters.Binary;

Step2:建立序列化的串流


BinaryFormatter formatter = new BinaryFormatter();

Step3:開始序列化(serialize)


Stream output = File.Create(file_name);
formatter.Serialize(output, objectToSerialize);
output.Close();

Step4:反序列化(deserialize)


Stream input = File.OpenRead(file_name);
SomeObj obj = (SomeObj)formatter.Deserialize(input);
input.Close();

四、二進制檔案讀寫

  除了文字檔,我們也可能保存 int、float 等變數的數值或是 byte 資料,這時候使用二進制檔案(binary)就比較方便了。


int value = 43;
using (FileStream output = File.Create("binarydata.dat")) { // 寫入整數值
BinaryWriter writer = new BinaryWriter(output);
writer.Write(value);
}
using (FileStream input = new FileStream(@"binarydata.dat", FileMode.Open)) { // 讀取整數值
BinaryReader reader = new BinaryReader(input);
int data = reader.ReadInt16();
}

  以上只針對最簡單的檔案讀寫來說明,其實不僅是檔案,包括網路串流、壓縮串流都是以類似的作法做輸出入,如欲深入瞭解請參閱其他書籍或 MSDN。

by autosun


原文出處:[C#] 檔案讀寫 @ 奧托森學習手札 :: 隨意窩 Xuite日誌
冷日
(冷日)
Webmaster
  • 註冊日: 2008/2/19
  • 來自:
  • 發表數: 15771
[轉貼](C#)寫出/讀取 XML之方法

(C#)寫出/讀取 XML之方法

寫出XML用拼文字的方式

先寫XML最上面那行

string mystr="<?xml version=\"1.0\" encoding=\"utf-8\" ?>"+Environment.NewLine+"<Data>"+ Environment.NewLine;

跑個For迴圈組合XML裡面的相關Node

For(條件條件)

{

 mystr += string.Format
("<Item>" + Environment.NewLine+
 "<Name>{0}</Name>"+Environment.NewLine+
 "<URL><![CDATA[{1}]]></URL>" + Environment.NewLine +
 "</Item>"+Environment.NewLine                   
 ,你要放的{0}的值,你要放的{1}的值
);
 mystr += Environment.NewLine;

}

 

然後寫出

StreamWriter sw = new StreamWriter(Application.StartupPath+"\\取個檔案的名字.xml", false, System.Text.Encoding.UTF8);



sw.Write(mystr);
sw.Flush();
sw.Close();

寫出後的XML會長這樣,注意用CDATA的功用是可以避開很多特殊字元,像是&、<..等等,

遇到這些字元的話不用CDATA會錯誤

<?xml version="1.0" encoding="utf-8" ?>
<Data>
<Item>
<Name>Cool1 </Name>
<URL><![CDATA[http://www.google.com]]></URL>
</Item>

<Item>
<Name>Cool2 </Name>
<URL><![CDATA[http://www.gamer.com.tw]]></URL>
</Item>
</DATA>

========================補充============================

如果要去改XML裡面某個Node節點之間的值的話,可用

XmlDocument xd = new XmlDocument();

 

xd.Load(
"my.xml");

 

XmlNode node = xd.SelectSingleNode( "//Hello");

 

node.InnerText = "你好";

 

xd.Save( "my.xml");

這樣會把原本的<Hello></Hello>修改成

<Hello>你好</Hello>

 

========================補充============================

接著下面是讀取


XmlDocument xd = new XmlDocument();

xd.Load("NameAndURL.xml");

XmlNodeList nodelist = xd.SelectNodes("//Item");

for (int i = 0; i < nodelist.Count; i++)
{
     richTextContent.AppendText(nodelist[i].SelectSingleNode("URL").InnerText);
     richTextContent2.AppendText(Environment.NewLine);
}

這樣會在RichTextBox控制項裡印出

http://www.google.com

http://www.gamer.com.tw


原文出處: (C#)寫出/讀取 XML之方法 @ 式門遁甲 :: 痞客邦 PIXNET ::
冷日補充:
會轉這篇是因為,冷日測試發現,用前面所說的辦法直接輸出的話,UltraEdit 判定輸出之檔案為純 DOS 格式,連 UTF-8 都不是!
雖然依照 VS2013 官方的說法,他輸出就是 UTF-8 了,但是冷日擔心害怕,所以還是檢查一下好了!
換言之,輸出時記得採用[code]new StreamWriter([String that you want to write out], System.Text.Encoding.UTF8);[code]即可!
前一個主題 | 下一個主題 | 頁首 | | |



Powered by XOOPS 2.0 © 2001-2008 The XOOPS Project|