MST

星途 面试题库

面试题:C#中如何使用StreamWriter向文件写入文本并处理异常

请编写一段C#代码,使用StreamWriter将一段给定的文本字符串写入到指定路径的文件中,并对可能出现的文件操作异常(如文件不存在、权限不足等)进行适当处理。
24.8万 热度难度
编程语言C#

知识考点

AI 面试

面试题答案

一键面试
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string textToWrite = "这是要写入文件的文本";
        string filePath = @"C:\example\test.txt";

        try
        {
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                writer.Write(textToWrite);
                Console.WriteLine("文本已成功写入文件。");
            }
        }
        catch (FileNotFoundException ex)
        {
            Console.WriteLine($"文件未找到异常: {ex.Message}");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"IO 异常: {ex.Message}");
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine($"权限不足异常: {ex.Message}");
        }
    }
}