C#读取文本文件并进行更新 [英] C# read text file and update it

查看:78
本文介绍了C#读取文本文件并进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在尝试创建一个读取* .txt文件的方法,问题显示我在文件内部有什么但是当我进入.txt并手动更新它时如果我尝试读取则不会更新它再次。



代码: http://prntscr.com/l00fzu [ ^ ]



我尝试了什么:



基本上我尝试了更多的东西,但我希望它像Printscreen中那样简单

So i am trying to create a method to read a *.txt file, the problem it shows me whats inside of the file but when i go in the .txt and update it manually it does not update if i try to read it again.

Code: http://prntscr.com/l00fzu[^]

What I have tried:

Basically i tried some more things but i want it to be simple like in the Printscreen

推荐答案

首先,不要给我们代码的屏幕转储:将实际代码复制并粘贴到您的问题中,这样我们就可以自己尝试,而无需重新输入。



其次,我们无法为您做任何事情:在代码运行时需要查看它,我们不能这样做,因为我们有无法访问您的系统。



因此,它将取决于你好。

幸运的是,你有一个工具可以帮助你找到正在发生的事情:调试器。如果您尚未使用它,那么快速使用Visual Studio调试器的Google应该会为您提供所需的信息。



在第一行放置一个断点在函数中,并通过调试器运行代码。然后查看您的代码,并查看您的数据并找出手动应该发生的事情。然后单步执行每一行检查您预期发生的情况正是如此。如果不是,那就是当你遇到问题时,你可以回溯(或者再次运行并仔细观察)以找出原因。


对不起,但是我们不能为你做到这一点 - 时间让你学习一门新的(非常非常有用的)技能:调试!
First off, don't give us screen dumps of your code: copy and paste the actual code into your question so we can try it ourselves without having to type it all back in.

Secondly, we can't do anything about this for you: it needs to be looked at while your code is running and we can't do that because we have no access to your system.

So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you haven't used it yet, then a quick Google for " Visual Studio debugger" should give you the info you need.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!


谢谢大家我会尝试调试就像OriginalGriff说的那样,我真的是一个初学者和编程,但谢谢大家!并且我没有在Web应用程序上工作这只是一个控制台中的学校项目,哦,还有一个问题是在IntelliJ(Java)中调试吗?



Thank You all i will try "Debugging" like OriginalGriff said, i'm really a beginner and programming though but thank you all! and no i am not working on web application this is just a school project in console, Oh and another question is there something like debugging in IntelliJ (Java)?

Thank You all i will try "Debugging" like OriginalGriff said, i'm really a beginner and programming though but thank you all!

So i was trying to use the the bug mode and something is not right i can't really seem to find the error, i will try to clarify things for you guys so first of all here is the code:

<pre>using System;
using System.IO;

// Aula de manipulação de files do tipo TXT
/* Procedimentos:
    1- criar uma string com o caminho e nome de um ficheiro a criar no disco
    2- Usar um método nativo para criar o ficheiro
    3- Usar um método nativo para ler o ficheiro*/

namespace Cap07_Aula01_FilesTxt
{
    class Program
    {
        static void Main(string[] args)
        {
            //String fileLocation = "D:\\Users\\a49240\\Desktop\\";
            String fileLocation = "C:\\Users\\Hugo\\Desktop\\";
            //String fileLocation = "C:\\Users\\????\\Desktop\\teste.txt";

            String name = "";    //Inicialização da string name

            //Pede o nome do fichero enquanto a extensão não for .txt ou o nome for menor que 4
            do
            {
                System.Console.WriteLine("Insira o nome do ficheiro! (A extensão tem de ser .txt)");
                name = Console.ReadLine();
            } while (name.Length < 4 || name.Substring(name.Length -4) != ".txt");

            //CreateFile(fileLocation); // Criar file
            CreateFile(name, fileLocation);
            WriteToFile(fileLocation+name); //Escrever dentro do ficheiro
            ReadFromFile(fileLocation + name);  //Lê o ficheiro TXT
        }

        /// <summary>
        /// Criar Ficheiro TXT
        /// </summary>
        /// <param name="file">recebe localização do ficheiro a criar</param>
        static void CreateFile(string file)
        {
            // Bloco try-catch para apanhar eventual exceção do tipo IOException
            try
            {
                //Tentativa de criação do ficheiro
                StreamWriter streamWriter = new StreamWriter(file); //Cria a file, caso não exista se exister abre-a
                System.Console.WriteLine("O ficheiro foi criado com sucesso");
                streamWriter.Close();                               //Necessário fechar sempre a file após uso
            }
            catch (IOException e)
            {
                // Se for gerada a exceção, esta é a resposta
                Console.WriteLine("O ficheiro não pode ser criado. \n\n\n");
                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentException e)
            {
                // Se for gerada a exceção, esta é a resposta
                Console.WriteLine("Há carateres ilegais no caminho indicado. \n\n\n");
                Console.WriteLine(e.StackTrace);
            }
        }

        /// <summary>
        /// Cria um Ficheiro TXT
        /// </summary>
        /// <param name="name">nome do ficheiro</param>
        /// <param name="location">localização (path) do ficheiro</param>
        static void CreateFile(string name,string location)
        {
            string file = location + name;  //Concatena a localização e o nome

            // Bloco try-catch para apanhar eventual exceção do tipo IOException
            try
            {
                //Tentativa de criação do ficheiro
                StreamWriter streamWriter = new StreamWriter(file); //Cria a file, caso não exista se exister abre-a
                System.Console.WriteLine("O ficheiro foi criado com sucesso");
                streamWriter.Close();                               //Necessário fechar sempre a file após uso
            }
            catch (IOException e)
            {
                // Se for gerada a exceção, esta é a resposta
                Console.WriteLine("O ficheiro não pode ser criado. \n\n\n");
                Console.WriteLine(e.StackTrace);
            }
            catch (ArgumentException e)
            {
                // Se for gerada a exceção, esta é a resposta
                Console.WriteLine("Há carateres ilegais no caminho indicado. \n\n\n");
                Console.WriteLine(e.StackTrace);
            }
        }

        /// <summary>
        /// Escrita no Ficheiro
        /// </summary>
        /// <param name="file">Localizaçao do ficheiro</param>
        static void WriteToFile(string file)
        {
            // Bloco try-catch para apanhar eventual exceção do tipo IOException
            try
            {
                StreamWriter sw = new StreamWriter(file); //Cria a file, caso não exista se existir abre-a
                sw.Write("Olá mundo");                    //Escreve na file
                sw.WriteLine(", eu sou o ");
                sw.Close(); //Necessário fechar a file para poder ser lido

                Console.WriteLine("Escrita no ficheiro com SUCESSO");
            }
            catch (IOException e)
            {
                Console.WriteLine("Escrita no ficheiro com erros... NABO\n\n\n");
                Console.WriteLine(e.StackTrace);
            }
            catch(ArgumentException e)
            {
                // Se for gerada a exceção esta é a resposta
                Console.WriteLine("Há carateres ilegais no caminho indicado . \n\n\n");
                Console.WriteLine(e.StackTrace);
            }
        }

        public static void ReadFromFile(String nameLocation)
        {
            try
            {
                String fileText = System.IO.File.ReadAllText(nameLocation);

                System.Console.WriteLine(fileText);

                System.Console.WriteLine("\nReadFromFile: O ficheiro foi lido");
            }
            catch (FileNotFoundException e)
            {
                System.Console.WriteLine("ReadFromFile: Ficheiro não encontrado");
            }
            catch (IOException e)
            {
                System.Console.WriteLine("ReadFromFile: Problemas com acesso ao ficheiro");
            }
            catch (Exception e)
            {
                System.Console.WriteLine("ReadFromFile: Apanhada qualquer outra exceção");
            }


        }
    }
}





我希望这有帮助,即使它是我的母语葡萄牙语,所以问题在于ReadFromFile方法,它可以读取并显示使用WriteToFile方法编写的内容(打印控制台帮助:https://prnt.sc/l04i8q [ ^ ]

此时可以,但是当我去记事本并尝试更改它时,当我再次执行我的代码时,它不会读取我刚更新的内容。我希望这样可以帮助你帮我解决这个问题。你有代码所以你可以尝试自己,即使它是葡萄牙语。



哦,我忘了提及我在Java中使用相同的Project我正在尝试将其复制到C#,它在Java中运行良好。





I hope this helps even though it's in my native language Portuguese, so the problem is in the ReadFromFile method it can read and show me what was written with the WriteToFile method (Print of console to help: https://prnt.sc/l04i8q[^]
At this point its all right but when i go to the notepad and try to change it, when i execute my code again it does not read what i just updated. I hope this can help you guys helping me to figure this out. You have the code so you can try it yourselves even if it is in Portuguese.

Oh i forgot to mention i have the same Project in Java i'm trying to copy it to C# it works fine in Java.

package com.company;

import java.io.*;
import java.util.Scanner;

// Aula de manipulação de files do tipo TXT
/* Procedimentos:
    1- criar uma string com o caminho e nome de um ficheiro a criar no disco
    2- Usar um método nativo para criar o ficheiro
    3- Usar um método nativo para ler o ficheiro*/

public class Main {

    public static void main(String[] args) {

        Scanner teclado = new Scanner(System.in);   //Criação e inicialização do scanner teclado

        String fileLocation = "D:\\Users\\a49240\\Desktop\\";
        //String fileLocation = "C:\\Users\\Hugo\\Desktop\\";
        //String fileLocation = "C:\\Users\\????\\Desktop\\teste.txt";

        String name;    //Inicialização da string name

        //Pede o nome do fichero enquanto a extensão não for .txt ou o nome for menor que 4
        do{
            System.out.println("Insira o nome do ficheiro! (A extensão tem de ser .txt)");
            name = teclado.nextLine();
        }while( name.length() < 4 || !name.substring(name.length() -4,name.length()) .equals(".txt"));

        System.out.println(name);   //Imprime o nome do ficheiro
        /////////////////////////////////////////////////////////////
        //  Criar File
        ////////////////////////////////////////////////////////////
        //CreateFile(fileLocation);
        CreateFile(name,fileLocation);

        //  Pausa para poder alterar o conteúdo da file
        try{
            System.out.print("\nPausa: Carregue numa tecla para continuar! ");
            System.in.read();
        }   catch (IOException e){
            System.out.print("ERRO na pausa:  \n\n "+e.getMessage());
        }

        //////////////////////////////////////////////////////////////
        //Escrita para um ficheiro
        /////////////////////////////////////////////////////////////

        WriteToFile(fileLocation+name,"Olá TGPSI"); // Escreve dentro do ficheiro

        //  Pausa para poder alterar o conteúdo da file
        try{
            System.out.print("\nPausa: Carregue numa tecla para continuar! ");
            System.in.read();
        }   catch (IOException e1){
            System.out.print("ERRO na pausa:  \n\n "+e1.getMessage());
        }

        ///////////////////////////////////////////////////////////////
        //  Ler um ficheiro txt
        ///////////////////////////////////////////////////////////////

        ReadFromFile(fileLocation+name);
    }

    /**
    * Criar Ficheiro TXT
     * @param nameLocation localização e nome do ficheiro
     * */
    public static void CreateFile(String nameLocation){

        // Se o ficheiro não existir na localização fornecida cria-o e guarda o controlo em "file"
        File file = new File(nameLocation); //Guarda apenas a localização da file não a cria

        // Se existir e não for uma pasta (diretoria)
        if(file.exists() && !file.isDirectory()){
            System.out.println("CreateFile: O ficheiro já existe");    //Avisa o utiliador que já existe o ficheiro
        }
        else{
            //Bloco try-catch para apanhar eventual exceção
            try{
                // Tentativa de abertura do ficheiro no modo de escrita
                FileWriter fileWriter = new FileWriter(file);

                //Se mostrar a seguinte notificação -> sabemos que criou o ficheiro
                System.out.println("CreateFile: O ficheiro foi criado");
            }
            catch (IOException e){
                // Se for gerada a exceção, esta é a resposta
                System.out.println(e.getMessage());
                System.out.println("CreateFile: O ficheiro não pode ser criado.");
            }
        }

        //TPC1
        // Pull do repo remoto
        // - Duplicar o método CreateFile. O novo vai receber 2 string: name e location da file
        //No método estas 2 strings devem ser concatenadas para poder executar o resto do código do método, que sera EXATAMENTE igual.
        //Na main o nome da file, deve ser pedido ao utilizador.
        //Enquanto .txt não estiver nos ultimos 4 carateres da string inserida o programa continua a pedir o nome (pesquisar como extrair os ultimos 4 carateres de uma string"sub strings"))
        //Commit e Push.
    }

    /**
     * Cria um ficheiro TXT
     * @param name  Nome do ficheiro
     * @param location  Localização do ficheiro
     */
    public static void CreateFile(String name,String location){

        String nameLocation = location+name;    //Concatena a localização e o nome

        // Se o ficheiro não existir na localização fornecida cria-o e guarda o controlo em "file"
        File file = new File(nameLocation); //Guarda apenas a localização da file não a cria

        // Se existir e não for uma pasta (diretoria)
        if(file.exists() && !file.isDirectory()){
            System.out.println("CreateFile: O ficheiro já existe");    //Avisa o utiliador que já existe o ficheiro
        }
        else{
            //Bloco try-catch para apanhar eventual exceção
            try{
                // Tentativa de abertura do ficheiro no modo de escrita
                FileWriter fileWriter = new FileWriter(file);

                //Se mostrar a seguinte notificação -> sabemos que criou o ficheiro
                System.out.println("CreateFile: O ficheiro foi criado");
                fileWriter.close();
            }
            catch (IOException e){
                // Se for gerada a exceção, esta é a resposta
                System.out.println(e.getMessage());
                System.out.println("CreateFile: O ficheiro não pode ser criado.");
            }
        }
    }

    /**
     * Escrita no ficheiro
     * Neste caso declaramos os ponteiros fora do try-catch porque vamos precisar de verificar se o ficheiro já existe
     * Se sim, abre-o e acrescente texto ao que já la está
     * Se não, cria-o e escreve o texto pretendido.
     * @param nameLocation Localização do ficheiro
     * @param blablabla    texto a escrever na file
     */
    public static void WriteToFile(String nameLocation, String blablabla){

        //Ponteiros de manipulação da file, fora do try-catch
        FileWriter fw;
        PrintWriter pw;

        try{
            //  Se file não existe cria-a e escreve, caso contrário abre-a para escrever
            File file = new File(nameLocation);
            if(file.exists() && !file.isDirectory()){
                fw = new FileWriter(nameLocation, true); // o 2º parametro, true, indica que o teste é para acrescentar
                pw = new PrintWriter(fw);       //Cria o ponteiro para escrever no ficheiro fw
            }
            else{
                // Abertura da file. FileWriter cria um ponteiro com propriedades de escrita
                fw = new FileWriter(nameLocation);  //Sem 2º parametro, indica que escreve de raiz
                pw = new PrintWriter(fw);           //Cria o ponteiro para escrever no ficheiro fw
            }

            //Escreve na file
            pw.println(blablabla);  //Escreve na file
            pw.close();             //Necessário fechar o objeto de escrita na file para poder ser aberta posteriormente
            fw.close();             //Necessário fechar o objeto de abertura da file para poder ser aberto posteriormente


            System.out.println("WriteToFile: O ficheiro foi atualizado com texto.");
        }
        catch (IOException e){
            //Se for gerada a exceção, esta é a resposta
            System.out.println("WriteToFile: O ficheiro não pode ser aberto.");
            System.out.println(e.getMessage());
        }
    }

    /**
     * Leitura do ficheiro TXT
     * @param nameLocation Localização e nome do ficheiro
     */
    public static void ReadFromFile(String nameLocation){
        try{
            //  Abertura da file em modo de Leitura
            FileReader fr = new FileReader(nameLocation);

            //  Criação de um bloco de memória para recolher o texto da file
            BufferedReader br = new BufferedReader(fr);

            // Ciclo para extrair o texto do bloco de memória para a string
            String fileText;
            while ((fileText = br.readLine())!=null){
                System.out.println(fileText);
            }
            //  Encerramento do bloco de memória da file.
            br.close();
            fr.close();

            System.out.println("\nReadFromFile: O ficheiro foi lido");
        }
        catch(FileNotFoundException e){
            System.out.println("ReadFromFile: Ficheiro não encontrado");
        }
        catch(IOException e){
            System.out.println("ReadFromFile: Problemas com acesso ao ficheiro");
        }
        catch(Exception e){
            System.out.println("ReadFromFile: Apanhada qualquer outra exceção");
        }


    }
}


这篇关于C#读取文本文件并进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆