C++ CLI Need some guidance :)

Greetings,

Thanks for answering my last question fellas.

Program: Visual Studio 2010 C++/CLI Windows Form

what my program does:

1) Read the filepath that I have saved in a text file.

1
2
String^ storedtextdata= System::IO::File::ReadAllText("example.txt");
			


2) Execute the file.

Process::Start(storedtextdata);

Now what happens is whenever I click it and I enter an invalid file or blank my program crashes. Now I was thinking of making an If Else statement.

It would like something like this, i'm just not sure what to put in the IF condition.

3) If Unable to Execute File, Give Message Box with error.


1
2
3
4
5

if(storedtextdata != what do i put here exactly for condition.... )
{
Process::Start(storedtextdata);
}else MessageBox::Show("unable to read file");


closed account (z05DSL3A)
Look at something like:
1
2
3
4
5
6
7
8
String ^ file_str = <your stored data>->Trim();

FileInfo ^ file_info = gcnew FileInfo(file_str);

if(file_info->Exists)
{
    // Do your thing here
}


ps when you get time read up on exception handling.
http://msdn.microsoft.com/en-us/library/hh875008.aspx
Last edited on by Canis lupus
Think a try-catch would be required. Something like this. IIRC.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
System::String^ myfile = L"myfile.txt" ;

if( System::IO::File::Exists(myfile) )
{
    try
    {
        System::String^ process_path = System::IO::File::ReadAllText(myfile)->Trim() ;
        System::Diagnostics::Process::Start(process_path) ;
        System::Console::Write( "ok.\n" ) ; 
    }
    catch( System::Exception^ e )
    {
        System::Console::Write( "error: " + e->ToString() + '\n' ) ;
    }
}
else System::Console::Write( "failed to open file " + myfile + '\n' ) ;

@JLBorges

Your method works great except I can't get the Error message to show. Other than that it no longer crashes my program , i'm gonna play with it and see if i can fix it, can you help me with the code for that?
You may be running a GUI program without a console.

Try something like System::Windows::Forms::MessageBox::Show() in place of System::Console::Write()

1
2
// System::Console::Write( "error: " + e->ToString() + '\n' ) ;
System::Windows::Forms::MessageBox::Show( "error: " + e->ToString() ) ;

or something like that; and likewise for the other messages.

EDIT: Yeah, MessageBox::Show(). Picked that up from the first post.
Last edited on
Topic archived. No new replies allowed.