相关疑难解决方法(0)

如果不存在,则创建.txt文件,如果它确实附加了新行

我想创建一个.txt文件并写入它,如果该文件已经存在,我只想添加更多行:

string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
    File.Create(path);
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The very first line!");
    tw.Close();
}
else if (File.Exists(path))
{
    TextWriter tw = new StreamWriter(path);
    tw.WriteLine("The next line!");
    tw.Close(); 
}
Run Code Online (Sandbox Code Playgroud)

但是第一行似乎总是被覆盖......我怎么能避免写在同一行(我在循环中使用它)?

我知道这是一件非常简单的事情,但我WriteLine之前从未使用过这种方法.我对C#完全不熟悉.

c# text-files

150
推荐指数
7
解决办法
40万
查看次数

在C#中将文本添加到文件的开头和结尾

我有一个进程可以获取一系列"xml"文件.我把xml放在引号中的原因是文件中的文本没有一个根元素,它使得xml无效.在我的处理中,我想纠正这个并打开每个文件,在每个文件的开头和结尾添加一个根节点,然后将其关闭.这是我的想法,但这涉及打开文件,读取整个文件,在节点上标记,然后写出整个文件.这些文件的大小可能超过20 MB.

        foreach (FileInfo file in files)
        {
            //open the file
            StreamReader sr = new StreamReader(file.FullName);

            // add the opening and closing tags
            string text = "<root>" + sr.ReadToEnd() + "<root>";
            sr.Close();

            // now open the same file for writing
            StreamWriter sw = new StreamWriter(file.FullName, false);
            sw.Write(text);
            sw.Close();
        }
Run Code Online (Sandbox Code Playgroud)

有什么建议?

c# xml file-io

6
推荐指数
3
解决办法
1万
查看次数

将行添加到文件开头

我正在尝试在文本文件的开头添加一个新行.我首先打开文件,append但只允许我使用write_all写入文件的末尾,至少这是我得到的结果.如果我正确阅读文档,这是设计的.

我试过玩seek,但这并没有解决它.

这就是我目前所拥有的:

let mut file = OpenOptions::new().append(true).open(&file_path).unwrap();
file.seek(SeekFrom::Start(0));
file.write_all(b"Cool days\n");
Run Code Online (Sandbox Code Playgroud)

如果我打开文件write,我最终会覆盖数据而不是添加.用Rust实现这个目标的合适方法是什么?

io file rust

4
推荐指数
1
解决办法
765
查看次数

如何"ToString"大量的字符数组?

我有以下代码:

public static void PrependEntitiesToFile(string pathToFile)
{
    char[] buffer = new char[10000];
    FileInfo file = new FileInfo(pathToFile);

    string renamedFile = file.FullName + ".orig";
    System.IO.File.Move(file.FullName, renamedFile);

    using (StreamReader sr = new StreamReader(renamedFile))
    using (StreamWriter sw = new StreamWriter(file.FullName, false))
    {
        string entityDeclaration = "foo";
        sw.Write(entityDeclaration);
        string strFileContents = string.Empty;
        int read;
        while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                strFileContents += buffer[i].ToString();
            }
        }
        sw.Write(strFileContents, 0, strFileContents.Length);

    }

    System.IO.File.Delete(renamedFile);
} …
Run Code Online (Sandbox Code Playgroud)

c#

0
推荐指数
1
解决办法
141
查看次数

标签 统计

c# ×3

file ×1

file-io ×1

io ×1

rust ×1

text-files ×1

xml ×1