在C#Console应用中生成文件路由时获取错误的文件路径

问题描述 投票:0回答:1

您好,我试图在C#控制台应用程序中读取SQL脚本。抱歉,如果这是超基本的,但是由于生成它的文件路径总是会启动项目的bin文件夹,因此出现问题。

        public static void ApiResources(IConfiguration config, string testUrlExtension)
        {
            try
            {
                var azureDatabaseUrl = String.Format(config["SqlDatabase:BaseUrl"], $"test{testUrlExtension}");

                SqlConnectionStringBuilder connBuilder = new SqlConnectionStringBuilder();
                connBuilder.DataSource = azureDatabaseUrl;
                connBuilder.UserID = config["SqlDatabase:ZupaKeyReleaseUserName"];
                connBuilder.Password = config["SqlDatabase:ZupaKeyReleasePassword"];
                connBuilder.InitialCatalog = "zupaauthentication";

                using (SqlConnection connection = new SqlConnection(connBuilder.ConnectionString))
                {
                    using (SqlCommand command = connection.CreateCommand())
                    {
                        connection.Open();
                        var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
                        var routeToApiResourseSqlScript = $"{GetLocalPathToProject}Zupa.ReleaseDeploymentAutoConfigure\\Zupa.ReleaseDeploymentAutoConfigure\\Sql\\Scripts\\";
                        var apiResourcesFileName = "AddApiResorces.sql";
                        var fullPathToSqlScript = $"{routeToApiResourseSqlScript}{apiResourcesFileName}";

                        command.CommandText = File.ReadAllText(fullPathToSqlScript);
                        command.ExecuteNonQuery();

                        connection.Close();
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine(e.InnerException);
            }
        }

正在接收的错误如下:

出了点问题,请重新配置发行版。System.IO.IOException:文件名,目录名称或卷标签语法不正确。 :

'C:\ Zupa_Source_Code \ Zupa.ReleaseDeploymentAutoConfigure \ Zupa.ReleaseDeploymentAutoConfigure \ bin \ Debug \ netcoreapp3.1 \ file:\ C:\ Zupa_Source_Code \ Zupa.ReleaseDeploymentAutoConfigure \ Zupa.ReleaseDeploymentAutoConfigure \ Sql \ Scripts \

正确的路径被添加到bin目录的末尾,它是

文件:\ C:\ Zupa_Source_Code \ Zupa.ReleaseDeploymentAutoConfigure \ Zupa.ReleaseDeploymentAutoConfigure \ Sql \ Scripts \ AddApiResorces.sql

谢谢,克里斯。

c# sql file console-application readfile
1个回答
0
投票

更改此行中的“ CodeBase”

var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];

将成为位置:

var GetLocalPathToProject = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location).Split("Zupa.ReleaseDeploymentAutoConfigure")[0];
© www.soinside.com 2019 - 2024. All rights reserved.