0

好的,我的问题是,当我尝试访问文件时,路径的文件名来自 DataTable,它只是找不到该文件。

当我从文本文件中解析文件名或只是在字符串中硬编码时,我已经对其进行了测试......当然这项工作>_<

当我从数据表中字符串文件名时,只是不知道差异在哪里。

它构建的字符串如下所示:

C:\Server\system/somefile.dat

这是代码:

    string accountConnectionString = ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        LoadFileChecks();
    }

    public SqlConnection GetAccountConnection()
    {
        SqlConnection connection = new SqlConnection(accountConnectionString);
        connection.Open();
        return connection;
    }


    public DataTable getFilecheck()
    {
        using (var con = GetAccountConnection())
        {
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tFilecheck", con);
            DataTable ds = new DataTable("Filecheck");
            da.Fill(ds);
            con.Close();
            return ds;
        }
    }

    public void LoadFileChecks()
    {
        DataTable table = getFilecheck();
        string localPath = Application.StartupPath;

        foreach (DataRow row in table.Rows)
        {
            string line = row["sFilename"].ToString();

            string FilePath = localPath + "\\" + line;
            if (!File.Exists(FilePath))
            {
                MessageBox.Show("File not found");
                continue;
            }
        }

    }
4

2 回答 2

0

首先,Application.StartupPath取决于您如何部署应用程序 exe。

string localPath = Application.StartupPath;

调试时将是当前执行路径(例如 project\bin\Debug)

其次,您不需要使用转义每个反斜杠\\

样品,而不是..

string path = "C:\\Server\\system";

尝试转义字符串@

string path = @"C:\Server\system";

然后 Path.Combine 与文件名

string fileName = row["sFilename"].ToString();
string filePath = Path.Combine(path, fileName); 
//Path.Combine(@"C:\Server\system", "somefile.dat");
于 2012-12-27T06:44:05.263 回答
0

这是一个 .net 网络应用程序吗?如果是,您应该使用更改服务器路径的路径

path = Server.MapPath(path);
于 2012-12-27T06:50:25.763 回答