C#把字符串写入文件

记录C#写文件的几种方式:

  • System.IO.File类提供用于创建,复制,删除,移动和打开单个文件的静态方法,方便操作文本文件。例如下面的例子,一行代码即可完成写文件操作,创建一个新文件,将内容写入文件,然后关闭文件。如果目标文件已存在,则会覆盖。
  • System.IO.StreamWriter用于将字符写入流,支持常见编码格式,支持append,写完后别忘了Close()或者Dispose(true)。
using System.IO;

namespace WriteFile
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteText();
            WriteLine();
            WriteSelectedString();
            WriteAppend();
        }

        // 写字符串
        public static void WriteText()
        {
            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. ";

            File.WriteAllText("WriteText.txt", text);
        }

        // 写多行
        public static void WriteLine()
        {
            string[] lines =
            {
                "First line", "Second line", "Third line"
            };

            File.WriteAllLines("WriteLines1.txt", lines);
        }

        // 有选择地写
        public static void WriteSelectedString()
        {
            string[] lines = { "First line", "Second line", "Third line" };
            StreamWriter file = new StreamWriter("WriteLines2.txt");

            foreach (string line in lines)
            {
                if (!line.Contains("Second"))
                {
                    file.WriteLine(line);
                }
            }
            file.Close();
        }

        // 在文件末尾续写
        public static void WriteAppend()
        {
            StreamWriter file = new StreamWriter("WriteLines2.txt", append: true);
            file.WriteLineAsync("Fourth line");
            file.Close();
        }
    }
}

 以上是.NET Framework 4.x支持的方法,.NET 6的类似操作参考How to write to a text file

C#中,有多种方法可以将HTML字符串写入PDF文件,以下为你介绍两种常见的实现方式: ### 使用iText7 iText7是一个强大的PDF处理库,可以将HTML字符串转换为PDF文件。以下是示例代码: ```csharp using iText.Html2pdf.Resolver.Font; using iText.Html2pdf; using System.IO; // HTML 字符串 string htmlContent = @" <html> <head> <title>Net 分享</title> </head> <body> <h1></h1> <h1>Net 分享</h1> <p>欢迎使用 iText7-一个 HTML 转 PDF </p> </body> </html>"; // 输出 PDF 文件路径 string pdfFilePath = "output_from_string.pdf"; HtmlConverter.ConvertToPdf(htmlContent, new FileStream(pdfFilePath, FileMode.Create), new ConverterProperties().SetFontProvider(new DefaultFontProvider(true, true, true))); // 将 HTML 字符串转换为 PDF //HtmlConverter.ConvertToPdf(htmlContent, new FileStream(pdfFilePath, FileMode.Create)); System.Console.WriteLine("HTML 字符串已成功转换为 PDF"); ``` 上述代码通过`HtmlConverter.ConvertToPdf`方法将HTML字符串转换为PDF文件,并保存到指定路径。同时,使用`DefaultFontProvider`来处理字体问题,确保PDF文件能正确显示文字[^1]。 ### 使用OpenHtmlToPdf OpenHtmlToPdf是基于wkhtmltopdf二次开发的插件,也能实现HTML字符串到PDF文件的转换。示例代码如下: ```csharp using OpenHtmlToPdf; using System; using System.Net; using System.Text; using (WebClient wc = new WebClient()) { wc.Encoding = Encoding.UTF8; string html = "<html><body><h1>示例标题</h1><p>这是一个示例段落。</p></body></html>"; var document = Pdf.From(html) .OfSize(OpenHtmlToPdf.PaperSize.LetterRotated) .WithGlobalSetting("margin.top", "0.4cm"); if (IntPtr.Size == 4) { document = document.WithObjectSetting("load.zoomFactor", "1.5"); } var result = document.Content(); // 这里可以将结果保存到文件 File.WriteAllBytes("output.pdf", result); // 如果是在Web环境中返回PDF文件 // HttpContext.Current.Response.Clear(); // HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=PDF" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".pdf"); // HttpContext.Current.Response.ContentType = "application/octet-stream"; // HttpContext.Current.Response.BinaryWrite(result); // HttpContext.Current.Response.End(); } ``` 此代码通过`Pdf.From`方法传入HTML字符串,对PDF的页面大小、边距等进行设置,最后将生成的PDF内容保存到文件中。若在Web环境中,还可以将PDF文件作为响应返回给客户端[^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值