0

I am stuck in creating a directory with C++Builder. If you check this here and here, I find examples for my case, but when I try to use them, none of them work for me! For example, the following code for creating a directory, where the edSourcePath->Text value has been defined.

Unfortunately the documentation is not complete.

try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (...)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

The error message says TDirectory is not a class or namespace.

Another question is, how can I pass the source path and directory name by CreateDirectory(edSourcePath->Text)?

4

1 回答 1

2

您看到的是编译时错误,而不是运行时错误。编译器找不到TDirectory类的定义。您需要在中定义#include的头文件TDirectory,例如:

#include <System.IOUtils.hpp> // <-- add this!

try
{
    /* Create directory to specified path */
    TDirectory::CreateDirectory(edSourcePath->Text);

    // or, if either DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE or
    // NO_USING_NAMESPACE_SYSTEM_IOUTILS is defined, you need
    // to use the fully qualified name instead:
    //
    // System::Ioutils::TDirectory::CreateDirectory(edSourcePath->Text);
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg("Incorrect path.\n" + e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

但是请注意,仅当输入不是有效的格式化路径时才会TDirectory::CreateDirectory()引发异常。String如果实际目录创建失败,它不会抛出异常。事实上,没有办法自己检测到这种情况TDirectory::CreateDirectory(),你必须TDirectory::Exists()事后检查:

#include <System.IOUtils.hpp>

try
{
    /* Create directory to specified path */
    String path = edSourcePath->Text;
    TDirectory::CreateDirectory(path);
    if (!TDirectory::Exists(path))
        throw Exception("Error creating directory");
}
catch (const Exception &e)
{
    /* Catch the possible exceptions */
    MessageDlg(e.Message, mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}

否则,TDirectory::CreateDirectory()它只是一个验证包装器System::Sysutils::ForceDirectories(),它有一个bool返回值。因此,您可以直接调用该函数:

#include <System.SysUtils.hpp>

/* Create directory to specified path */
if (!ForceDirectories(edSourcePath->Text)) // or: System::Sysutils::ForceDirectories(...), if needed
{
    MessageDlg("Error creating directory", mtError, TMsgDlgButtons() << mbOK, NULL);
    return;
}
于 2019-01-21T18:49:14.273 回答