简体   繁体   English

在C#控制台应用程序的Release文件夹中读取和写入文本文件

[英]Reading and Writing to a Text File within the Release Folder of a C# Console App

I have a C# console application that uses text from a txt file as a parameter for a SQL query. 我有一个C#控制台应用程序,它使用txt文件中的文本作为SQL查询的参数。 After the query runs, it stores the highest primary key in the text file. 查询运行后,它将最高主键存储在文本文件中。 The next time it runs, it uses the first line of that text file in the WHERE statement to grab primary keys higher than the previously stored one. 下次运行时,它将使用WHERE语句中该文本文件的第一行来获取比先前存储的更高的主键。 Here's the code I'm using: 这是我正在使用的代码:

// get latest primary key //获取最新的主键

static String mostRecentID= File.ReadAllLines(@"C:\DataStorage\latestID.txt").First().Trim();

// run the query //运行查询

SELECT * FROM whatever WHERE pk > mostRecentID

// store latest primary key //存储最新的主键

DataRow mostRecentIDRow= exportTable.Select().FirstOrDefault();
        if (mostRecentIDRow!= null)
        {
            mostRecentID = mostRecentIDRow[0].ToString().Trim();
            File.WriteAllLines(@"C:\DataStorage\latestID.txt", new String[] { mostRecentID});
        }

I need to be able to read and write to this text file independent of where the program or the file is located. 我需要能够独立于程序或文件所在的位置读取和写入此文本文件。 Is there a way to do this while keeping it in the release folder of the program? 有一种方法可以将其保存在程序的发布文件夹中吗?

If you are trying to keep the text file in the root location of the application use this 如果您尝试将文本文件保留在应用程序的根目录中,请使用此选项

string file = Path.Combine(
     System.Reflection.Assembly.GetExecutingAssembly().Location, "latestID.txt");

you can get the path of the current running assembly like this: 您可以像这样获取当前正在运行的程序集的路径:

 string path = System.IO.Path.GetDirectoryName( 
  System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );

and there you can save/load your file 在那里您可以保存/加载文件

Just use this variable: 只需使用此变量:

 string myDirectory = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

to get the directory where you program executes. 获取您的程序执行目录。

So when you place your .txt in Release Folder you can use: 因此,当您将.txt放置在Release Folder中时,可以使用:

 File.WriteAllLines(myDirectory + "/" + "latestID.txt", new String[] { mostRecentID});

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

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