ASP.NET入门之向文件操作

本文介绍了使用 C# 进行文件操作的方法,包括向文件写入文本、从文件读取文本、将文本追加到文件、移动文件等常见操作。通过示例展示了如何使用 StreamWriter 和 StreamReader 类来完成这些任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ContractedBlock.gifExpandedBlockStart.gifCode
向文件写入文本using System;
using System.IO;

class Test 
{
    
public static void Main() 
    {
        
// Create an instance of StreamWriter to write text to a file.
        
// The using statement also closes the StreamWriter.
        using (StreamWriter sw = new StreamWriter("TestFile.txt")) 
        {
            
// Add some text to the file.
            sw.Write("This is the ");
            sw.WriteLine(
"header for the file.");
            sw.WriteLine(
"-------------------");
            
// Arbitrary objects can also be written to the file.
            sw.Write("The date is: ");
            sw.WriteLine(DateTime.Now);
        }
    }
}


 

using System;
using System.IO;
public class TextToFile 
{
    
private const string FILE_NAME = "MyFile.txt";
    
public static void Main(String[] args) 
    {
        
if (File.Exists(FILE_NAME)) 
        {
            Console.WriteLine(
"{0} already exists.", FILE_NAME);
            
return;
        }
        StreamWriter sr 
= File.CreateText(FILE_NAME);
        sr.WriteLine (
"This is my file.");
        sr.WriteLine (
"I can write ints {0} or floats {1}, and so on."
            
14.2);
        sr.Close();
    }
}




从文件读取文本


using System;
using System.IO;

class Test 
{
    
public static void Main() 
    {
        
try 
        {
            
// Create an instance of StreamReader to read from a file.
            
// The using statement also closes the StreamReader.
            using (StreamReader sr = new StreamReader("TestFile.txt")) 
            {
                String line;
                
// Read and display lines from the file until the end of 
                
// the file is reached.
                while ((line = sr.ReadLine()) != null
                {
                    Console.WriteLine(line);
                }
            }
        }
        
catch (Exception e) 
        {
            
// Let the user know what went wrong.
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}



 

using System;
using System.IO;
public class TextFromFile 
{
    
private const string FILE_NAME = "MyFile.txt";
    
public static void Main(String[] args) 
    {
        
if (!File.Exists(FILE_NAME)) 
        {
            Console.WriteLine(
"{0} does not exist.", FILE_NAME);
            
return;
        }
        StreamReader sr 
= File.OpenText(FILE_NAME);
        String input;
        
while ((input=sr.ReadLine())!=null
        {
            Console.WriteLine(input);
        }
        Console.WriteLine (
"The end of the stream has been reached.");
        sr.Close();
    }
}

File.AppendText 方法 创建一个 StreamWriter,它将 UTF
-8 编码文本追加到现有文件。

public static StreamWriter AppendText(
string path
);

参数
path 
要向其中追加内容的文件的路径。 
返回值
一个 StreamWriter,它将 UTF
-8 编码文本追加到现有文件。

将文本追加到文件



using System;
using System.IO;

class Test 
{
    
public static void Main() 
    {
        
string path = @"c:    empMyTest.txt";
        
// This text is added only once to the file.
        if (!File.Exists(path)) 
        {
            
// Create a file to write to.
            using (StreamWriter sw = File.CreateText(path)) 
            {
                sw.WriteLine(
"Hello");
                sw.WriteLine(
"And");
                sw.WriteLine(
"Welcome");
            }    
        }

        
// This text is always added, making the file longer over time
        
// if it is not deleted.
        using (StreamWriter sw = File.AppendText(path)) 
        {
            sw.WriteLine(
"This");
            sw.WriteLine(
"is Extra");
            sw.WriteLine(
"Text");
        }    

        
// Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) 
        {
            
string s = "";
            
while ((s = sr.ReadLine()) != null
            {
                Console.WriteLine(s);
            }
        }
    }
}




 

using System;
using System.IO;

class Test 
{
    
    
public static void Main() 
    {
        FileInfo fi 
= new FileInfo(@"c:    empMyTest.txt");

        
// This text is added only once to the file.
        if (!fi.Exists) 
        {
            
//Create a file to write to.
            using (StreamWriter sw = fi.CreateText()) 
            {
                sw.WriteLine(
"Hello");
                sw.WriteLine(
"And");
                sw.WriteLine(
"Welcome");
            }    
        }

        
// This text will always be added, making the file longer over time
        
// if it is not deleted.
        using (StreamWriter sw = fi.AppendText()) 
        {
            sw.WriteLine(
"This");
            sw.WriteLine(
"is Extra");
            sw.WriteLine(
"Text");
        }    

        
//Open the file to read from.
        using (StreamReader sr = fi.OpenText()) 
        {
            
string s = "";
            
while ((s = sr.ReadLine()) != null
            {
                Console.WriteLine(s);
            }
        }
    }
}
=====================================
using System;
using System.IO;

public class AppendTextTest 
{
    
public static void Main() 
    {
        
// Create a reference to a file, which might or might not exist.
        
// If it does not exist, it is not yet created.
        FileInfo fi = new FileInfo("temp.txt");
        
// Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine(
"Add as many lines as you like");
        sw.WriteLine(
"Add another line to the output");
        sw.Flush();
        sw.Close();
        
// Get the information out of the file and display it.
        
// Remember that the file might have other lines if it already existed.
        StreamReader sr = new StreamReader(fi.OpenRead());
        
while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}
移动一个文件将指定文件移到新位置,并提供指定新文件名的选项。
public static void Move(string sourceFileName,string destFileName);参数sourceFileName 要移动的文件的名称。 destFileName 文件的新路径。 using System;
using System.IO;

class Test 
{
    
public static void Main() 
    {
        
string path = @"c:    empMyTest.txt";
        
string path2 = path + "temp";
        
try 
        {
            
if (!File.Exists(path)) 
            {
                
// This statement ensures that the file is created,
                
// but the handle is not kept.
                using (FileStream fs = File.Create(path)) {}
            }

            
// Ensure that the target does not exist.
            if (File.Exists(path2))    
            File.Delete(path2);

            
// Move the file.
            File.Move(path, path2);
            Console.WriteLine(
"{0} was moved to {1}.", path, path2);

            
// See if the original exists now.
            if (File.Exists(path)) 
            {
                Console.WriteLine(
"The original file still exists, which is unexpected.");
            } 
            
else 
            {
                Console.WriteLine(
"The original file no longer exists, which is expected.");
            }            

        } 
        
catch (Exception e) 
        {
            Console.WriteLine(
"The process failed: {0}", e.ToString());
        }
    }
}

将一个文件移动至另一位置并重命名该文件。
using System;
using System.IO;

public class MoveToTest 
{
    
public static void Main() 
    {
        
// Create a reference to a file, which might or might not exist.
        
// If it does not exist, it is not yet created.
        FileInfo fi = new FileInfo("temp.txt");
        
// Create a writer, ready to add entries to the file.
        StreamWriter sw = fi.AppendText();
        sw.WriteLine(
"Add as many lines as you like");
        sw.WriteLine(
"Add another line to the output");
        sw.Flush();
        sw.Close();
        
// Ensure that the target file does not exist, since this is disallowed.
        if (File.Exists("newTemp.txt"))
            File.Delete(
"newTemp.txt");
        
// Move this file to another file.
        fi.MoveTo("newTemp.txt");
        
// Get the information out of the new file and display it.
        StreamReader sr = new StreamReader( fi.OpenRead() );
        Console.WriteLine(
"{0}This is the information in the new file "{1}":", Environment.NewLine, fi.Name);
        
while (sr.Peek() != -1)
            Console.WriteLine( sr.ReadLine() );
    }
}

转载于:https://www.cnblogs.com/luozhanbin/archive/2008/12/10/1351591.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值