繁体   English   中英

从文件读取并写入 C# 中的临时.txt 文件?

[英]Reading from file and writing to a temporary .txt file in C#?

我知道这个网站上有很多类似的主题,但我认为我经历了大部分,仍然无法调试这段代码。 我真的需要让这个工作。 我是 C# 和编程的新手。 Tho,我在 Java 中做了同样的任务,但由于某种原因,我不能让它在这里工作。 如果有人可以请投...

所以我有一些对象,我保存在.txt文件中,一行 = 一个 object 的数据。 该行的第一个数据是 object 的Id ,基本上是主键。 现在我正在实现CRUD操作,即更新。 此编辑 function 应该有助于该功能。

如果用户编辑某些选定的 object 属性,则该更改需要反映在.txt文件中。 So, I will go through every object/line in the file, write them to some temp.txt file, once I hit object which has same Id as the passed object o , that means I need to write that edited object to temp.txt . 之后,我需要将temp.txt重命名为原始文件并删除temp.txt

我尝试了一堆选项和组合,但没有一个奏效。

我确实确保GetTxtPath从我的项目中返回正确的绝对路径。

版本 1:

public static void edit(Transformable o, string fileName)
{
    try
    {
        if (!File.Exists(FileUtils.GetTxtPath("temp.txt")))
        {
            File.Create(FileUtils.GetTxtPath("temp.txt"));
        }
        using (FileStream stream = File.OpenRead(FileUtils.GetTxtPath(fileName)))
        using (FileStream writeStream = File.OpenWrite(FileUtils.GetTxtPath("temp.txt")))
        {
            StreamReader reader = new StreamReader(stream);
            StreamWriter writer = new StreamWriter(writeStream);

            String line;
            while ((line = reader.ReadLine()) != null)
            {
                if (!line.Equals(""))
                {
                    if (o.GetId() == getIdFromString(line))
                    {
                        writer.Write(o.WriteToFile());
                    }
                    else
                    {
                        writer.Write(line + "\n");
                    }
                }
                else
                {
                    continue;
                }
            }
        }
    }
    catch (FileNotFoundException e)
    {
        Console.WriteLine($"The file was not found: '{e}'");
    }
    catch (DirectoryNotFoundException e)
    {
        Console.WriteLine($"The directory was not found: '{e}'");
    }
    catch (IOException e)
    {
        Console.WriteLine($"The file could not be opened: '{e}'");
    }
}

public static string GetTxtPath(string fileName)
{
    var startDirectory =
    Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;

    var absPath = startDirectory + @"\data\" + fileName;
    return absPath;
}

private static int getIdFromString(string line)
{
    return Int32.Parse(line.Split('|')[0]);
}

版本 2:

public static void Edit(Transformable o, string fileName)
{
    try
    {
        if (!File.Exists(FileUtils.GetTxtPath("temp.txt")))
        {
            File.Create(FileUtils.GetTxtPath("temp.txt"));
        }

        using (StreamReader reader = FileUtils.GetTxtReader(fileName))
        using (StreamWriter writer = FileUtils.GetTxtWriter("temp.txt"))
        {
            String line;
            while ((line = reader.ReadLine()) != null)
            {
                if (!line.Equals(""))
                {
                    if (o.GetId() == getIdFromString(line))
                    {
                        writer.Write(o.WriteToFile());
                    }
                    else
                    {
                        writer.Write(line + "\n");
                    }
                }
                else
                {
                    continue;
                }
            }
        }

        File.Move(FileUtils.GetTxtPath("temp.txt"), FileUtils.GetTxtPath(fileName));
        File.Delete(FileUtils.GetTxtPath("temp.txt"));
        //Here I tied many differenet options but nonthing worked

        //Here is Java code which did the job of renaming and deleting
        //------------------------------------------------------------
        //    File original = FileUtils.getFileForName(fileName);

        //    File backUpFile = new File("backUp");

        //    Files.move(original.toPath(), backUpFile.toPath(),
        //            StandardCopyOption.REPLACE_EXISTING);

        //    File temporary = FileUtils.getFileForName(temporaryFilePath);
        //    temporary.renameTo(original);
        //    backUpFile.delete();

        //    File original = FileUtils.getFileForName(path);
        //--------------------------------------------------------
        //public static File getFileForName(String name)
        //{

        //    String dir = System.getProperty("user.dir");
        //    String sP = System.getProperty("file.separator");
        //    File dirData = new File(dir + sP + "src" + sP + "data");

        //    File file = new File(dirData.getAbsolutePath() + sP + name);

        //    return file;

        //}
        //---------------------------------------------------------------------
    }
    catch (FileNotFoundException e)
    {
        Console.WriteLine($"The file was not found: '{e}'");
    }
    catch (DirectoryNotFoundException e)
    {
        Console.WriteLine($"The directory was not found: '{e}'");
    }
    catch (IOException e)
    {
        Console.WriteLine($"The file could not be opened: '{e}'");
    }




public static StreamReader GetTxtReader(string fileName)
{
    var fileStream = new FileStream(GetTxtPath(fileName), FileMode.Open, FileAccess.Read);
    return new StreamReader(fileStream, Encoding.UTF8);
}

public static StreamWriter GetTxtWriter(string fileName)
{
    FileStream fileStream = new FileStream(GetTxtPath(fileName), FileMode.Append);
    return new StreamWriter(fileStream, Encoding.UTF8);
}
public static void Edit(Transformable o, string fileName)
{
    try
    {
        string tempName = "temp.txt"; // create here correct path

        using (var readStream = File.OpenRead(fileName))
        using (var writeStream = File.OpenWrite(tempName))
        using (var reader = new StreamReader(readStream))
        using (var writer = new StreamWriter(writeStream))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (!line.Equals(""))
                {
                    if (o.GetId() == GetId(line))
                    {
                        writer.WriteLine(o.ToWriteableString());
                    }
                    else
                    {
                        writer.WriteLine(line);
                    }
                }
            }
        }

        File.Delete(fileName);
        File.Move(tempName, fileName);
    }
    catch ...

}

File.OpenWrite方法打开现有文件或创建新文件以进行写入。 因此无需手动检查和创建文件。

您已经非常正确地将FileStreams包装在 using 语句中。 但是, StreamReaderStreamWriter也必须在使用后释放。

我重命名了一些方法,赋予它们符合 C# 中命名规则的名称: EditGetIdToWriteableString

不需要带有continue语句的else分支。

最后,只需使用File.DeleteFile.Move方法。

注意: int.Parse方法可以抛出同样需要处理的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM