2010-11-22 210 views
-1

我可以保存一個文件而不另存爲對話框嗎?用saveas對話框保存文件?

+2

有或沒​​有? – Bolu 2010-11-22 12:56:13

+3

實際上,「另存爲」對話框與*保存*(創建/寫入/覆蓋/附加)文件的行爲很少有關。 – Ani 2010-11-22 12:57:41

回答

1

你提的問題是非常模糊的,但服用野生刺吧:

是的,只是使用的類在System.IO namespace。例如,在FileStream class documentation中有一個例子;引用它:

using System; 
using System.IO; 
using System.Text; 

class Test 
{ 

    public static void Main() 
    { 
     string path = @"c:\temp\MyTest.txt"; 

     // Delete the file if it exists. 
     if (File.Exists(path)) 
     { 
      File.Delete(path); 
     } 

     //Create the file. 
     using (FileStream fs = File.Create(path)) 
     { 
      AddText(fs, "This is some text"); 
      AddText(fs, "This is some more text,"); 
      AddText(fs, "\r\nand this is on a new line"); 
      AddText(fs, "\r\n\r\nThe following is a subset of characters:\r\n"); 

      for (int i=1;i < 120;i++) 
      { 
       AddText(fs, Convert.ToChar(i).ToString()); 

      } 
     } 

     //Open the stream and read it back. 
     using (FileStream fs = File.OpenRead(path)) 
     { 
      byte[] b = new byte[1024]; 
      UTF8Encoding temp = new UTF8Encoding(true); 
      while (fs.Read(b,0,b.Length) > 0) 
      { 
       Console.WriteLine(temp.GetString(b)); 
      } 
     } 
    } 

    private static void AddText(FileStream fs, string value) 
    { 
     byte[] info = new UTF8Encoding(true).GetBytes(value); 
     fs.Write(info, 0, info.Length); 
    } 
} 

@All:同樣,這是從文檔引用,而不是原始代碼。

1

當然。您可以使用StreamWriter類:

FileInfo t = new FileInfo("f.txt"); 
StreamWriter Tex =t.CreateText(); 
Tex.WriteLine("Hello"); 
Tex.close(); 
1

是的,請查看File類。

3

是的,但你必須有一個文件名。文件對話框僅用於確定寫入文件的好文件名。