询问用户导出txt文件的路径 [英] Ask the path to user export txt files

查看:105
本文介绍了询问用户导出txt文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个允许用户将数据导出到txt的程序,但是我想首先询问用户创建txt的路径是什么。但是我没有找到替换功能,我正在添加一个变量。

对不起,如果这是一个狡猾的问题。



我尝试过:



 string path = @## Insert ## \ export.txt; 

Console.WriteLine(插入导出txt的路径:);
string temp = Console.ReadLine();
path = path.Replace($## Insert ##,{temp});

解决方案

## Insert ##,{temp});


我不认为Replace方法使用格式字符串,因为它们在此上下文中没有意义。请参阅 String.Replace Method(系统)| Microsoft Docs [ ^ ]。


为什么你甚至使用替换?您应该从用户获取文件夹路径,确保它存在或创建路径,然后使用Path.Combine()将文件名追加到路径。

  string  folderPath = Console.ReadLine(); 
if (!Directory.Exists(path)
{
// 目录路径不存在。尝试创建它
// 或询问用户是否应该创建它,然后创建它
// 如果被告知。
尝试
{
....
}
catch (...)
{
// < span class =code-comment>由于某种原因无法创建路径...
}
}

folderPath = Path.Combine( folderPath, export.txt);
...


I am trying to make a program that allows the user to export data to txt, however I want first to ask user what is the path to create the txt. However I'm not getting right the replace function, I doing adding a variable.
Sorry if it's a sily question.

What I have tried:

string path = @"##Insert##\export.txt";

        Console.WriteLine("Insert the path to export txt: ");
        string temp = Console.ReadLine();
        path = path.Replace($"##Insert##", "{temp}");

解决方案

"##Insert##", "{temp}");


I do not think that the Replace method uses format strings, as they have no meaning in this context. See String.Replace Method (System) | Microsoft Docs[^].


Why are you even using a Replace? You should be getting the folder path from the user, making sure it exists or you create the path, then you append the filename to the path using Path.Combine().

string folderPath = Console.ReadLine();
if (!Directory.Exists(path)
{
    // The directory path doesn't exist. Try to create it
    // or ask the user if it should be created, then create it
    // if told to.
    try
    {
        ....
    }
    catch (...)
    {
        // The path couldn't be created for some reason...
    }
}

folderPath = Path.Combine(folderPath, "export.txt");
...


这篇关于询问用户导出txt文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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