用C#读取文本文件 [英] text file reading in C#

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

问题描述

如何从文本文件中读取源路径和目标路径,并仅使用这些路径在c#.net windows应用程序中执行某些操作?

how to read source and destination paths from a text file and use only those paths to do some operation in c#.net windows application?

推荐答案

具体如何阅读它们取决于你如何将它们存储在文件中,但如果它们在不同的行上,最简单的方法是使用ReadAllLines:

Exactly how you read them depends on how you have them stored in the file, but if they are on separate lines the easiest way is to use ReadAllLines:
string[] paths = File.ReadAllLines(@"D:\Temp\myPaths.txt");
if (paths.Length >= 2)
   {
   string sourcePath = paths[0];
   string destPath = paths[1];
   ...
   }

如果您想从源头阅读:

If you then want to read from the source:

string data = File.ReadAllText(sourcePath);

或写入目的地:

Or write to the destination:

File.WriteAllText(destPath, data);

可能还有其他更合适的方法,具体取决于您想要读/写的内容/方式,但这取决于您的应用程序。

There may be other methods that are more appropriate, depending on what / how you want to read / write but that is up to your application.

根据建议,它取决于文本文件 content

例如,如果文件只包含源和目标路径,在不同的行上,您的任务非常简单:读取两行并将应用程序变量设置为其内容,然后根据这些变量的值执行所需的操作。
As suggested it depends on the text file content.
For instance if the file contains only source and destination path, on different lines, your task is really easy: read the two lines and set your application variables to their content, then perform required operation based on the values of such variables.


如果您的源和目标是单行以分隔符分隔的话

if your source and destination are in single line saperated by delimmeter then
StreamReader sr = new StreamReader("Your Text File Path");
            string[] Arr;
            string line = sr.ReadLine;
            Arr=line.Split(","); //if source & destination are in same line and some delimmeter separated like "," or any ";"
            MessageBox.Show(Arr[0], "Source");
            MessageBox.Show(Arr[1], "Destination");



否则如果在两行中则


else if in two lines then

string[] Arr = File.ReadAllLines("your text file path");
if (Arr.Length >= 2)
   {
   string source = Arr[0];
   string destination = Arr[1];
   ...
   }


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

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