【问题标题】:File.Exists(Path) always return false when get 'string (Path)' from text file从文本文件中获取“字符串(路径)”时,File.Exists(Path) 总是返回 false
【发布时间】:2021-05-19 01:04:10
【问题描述】:

我编写代码来接收文本文件的路径并将其存储在我公开声明的字符串变量中。 然后我想知道文件是否存在使用

System.IO.File.Exists(pathoffile)

但即使有文件,它也总是返回 false。 然后当我尝试像这样直接添加字符串路径时

public string propertyfile = @"C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt"

功能

System.IO.File.Exists(pathoffile)

返回真

我已经检查了从文本文件中读取的接收路径(字符串)。通过切断“\n”和“\r”并使用trim()。但它仍然返回false。 我错过了什么吗?这两者有什么区别?。我对这个 c# 太陌生了。我很不擅长提前道歉。

这是我的代码

public string pathfromread, partnumber, pathfile, portname, partnofromserial,propertypathfile; //Declare Variables
        public string propertyfile = @"C:\Users\PFA Wongsawat\Desktop\Properties.txt";
        public string pathoffile ;
        public string backuppath ;
        public string pdffolderpath  ;

private void propertyget()
        {
            if (File.Exists(propertyfile))
            {
                StreamReader readpropertyfile = new StreamReader(propertyfile);
                string readproperty;

                while ((readproperty = readpropertyfile.ReadLine()) != null)
                {
                    string[] propertyfromread = readproperty.Trim().Split('=');
                    if (propertyfromread.GetValue(0).ToString() == "pathoffile")
                    {
                        pathoffile = propertyfromread.GetValue(1).ToString();
                        pathoffile = pathoffile.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(pathoffile, "path file");
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "backuppath"))
                    {
                        backuppath = propertyfromread.GetValue(1).ToString();
                        backuppath = backuppath.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(backuppath);
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "pdffolderpath"))
                    {
                        pdffolderpath = propertyfromread.GetValue(1).ToString();
                        pdffolderpath = pdffolderpath.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(pdffolderpath);
                    }
                    else if ((propertyfromread.GetValue(0).ToString() == "portname"))
                    {
                        portname = propertyfromread.GetValue(1).ToString();
                        portname = portname.Replace("\n", "").Replace("\r", "");
                        MessageBox.Show(portname);
                    }
                }
            }

 private void Form1_Load(object sender, EventArgs e)
        {
            propertyget();

            dv = dt.DefaultView; //set dv index count to != 0 to prevent error from null input when click on remove button

            if (System.IO.File.Exists(pathoffile))//Check if file exist or not
            {

            }
            else
            {
                try
                {
                    MessageBox.Show("Database Text File Missing. Please Select New File", "Database Text File Missing", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    OpenFileDialog regispath = new OpenFileDialog();
                    regispath.Title = "Select Database Text File (part_no_and_path_list.txt)";
                    regispath.Multiselect = false;
                    regispath.Filter = "Text file (*.txt)|*.txt";
                    regispath.RestoreDirectory = true;
                    regispath.ShowDialog();
                    pathfile = regispath.FileName;
                    File.Copy(pathfile, pathoffile);
                }
                catch
                {

这是我的属性文本文件

pathoffile=@"C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt"
backuppath=@"C:\Users\PFA Wongsawat\Documents\part_no_and_path_list.txt"
pdffolderpath=@"C:\Users\PFA Wongsawat\Downloads\"
portname=COM3

在这种情况下,结果总是一个消息框显示“缺少数据库文本文件。请选择新文件”

谢谢你,对不起我的英语不好。

【问题讨论】:

  • 我猜你的格式/结构有误,打印出来看看区别
  • 我建议您将每种情况下的值打印到控制台。您会看到,在工作案例中,没有双引号,也没有 @ 符号。这些是字符串的 C# 语法 的一部分。您的属性文件不是 C#。 (顺便说一句,我还建议阅读 .NET 命名约定,以及使用 array[index] 语法而不是调用 GetValue 的数组访问。)
  • @JonSkeet 谢谢!如您所说,我将代码更改为使用 array[index] 。而且效果很好。

标签: c# file-io configuration load text-files


【解决方案1】:

您不要将@"" 放在文本文件中,您只需将它们放在代码中,因为 c# 编译器就是这样知道它们是字符串(并且知道不将斜杠解释为转义字符)

让你的文本文件看起来像:

pathoffile=C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt

我也建议你使用:

Split(new []{'='}, 2)

这将允许您在路径中使用 =,通过使 split 返回最多 2 个拆分值;任何合法存在于路径中的 = 都将被保留

实际上,我建议您使用 c# 具有的各种内置设置机制之一;大约 25 年我们不需要读写自己的配置文件

如果你真的想继续自己开发,你可以使用字典来大量减少你的代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class Settings{
    private Dictionary<string,string> _conf = new Dictionary<string,string>();

    public string PathOfFile {
      get => _conf["pathoffile"];
    }

    public void ReadConfig(){
      File.ReadAllLines("conf.txt").ToDictionary(
        x => x.Split(new[]{'='},2)[0],
        x => x.Split(new[]{'='},2)[1]
      );
    }
}

是的,这就是你所需要的。每次你想添加另一个设置时,添加另一个属性(如公共字符串 PathOfFile),向文件添加另一个爱,并确保属性中的字符串与文件中的行匹配

在其他领域,请阅读 c# 命名约定; PublicThingsAreNamedLikeThis、_privateLikeThis、localLikeThis、neverlikethis

【讨论】:

  • 没问题!关于如何使用堆栈溢出的快速教程:当有人写出您认为有用或有帮助的答案时,请单击数字上方的向上箭头。当有人写下您最终用来解决问题的答案时,单击灰色勾号将其变为绿色。任何数量的答案都可以标记为有用,包括您勾选的答案,但只能勾选一个答案。解决问题后勾选答案 - 它会改变仪表板上问题的外观,以便人们知道您不是仍在寻找答案
【解决方案2】:

谢谢我已经解决了这个问题

通过像这样从属性文本文件的路径中删除“@”和“”“”。

pathoffile=C:\Users\PFA Wongsawat\Desktop\part_no_and_path_list.txt
backuppath=C:\Users\PFA Wongsawat\Documents\part_no_and_path_list.txt
pdffolderpath=C:\Users\PFA Wongsawat\Downloads\
portname=COM3

我看不到这个的原因是因为我通过在消息框中看到结果来调试程序并且它与真实的不匹配。谢谢。

【讨论】:

  • 了解Visual Studio调试器很有帮助。创建仅用于调试的文本框很麻烦并且可能会造成混淆。这是帮助您入门的教程:docs.microsoft.com/en-us/visualstudio/get-started/csharp/…
  • @RudolfJan 谢谢你的朋友。可惜我以前没有研究过这个。
  • 别难过,趁着机会学点新东西。顺便说一句,你也可能喜欢 IAmTimCorey。查找 YouTube。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-22
  • 2015-10-20
  • 2010-10-29
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2019-10-06
相关资源
最近更新 更多