Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
iam porting a c++ function to c#

code of c++ is

int CCategory::CheckFileOrFolder(CString str)
{
	int iRet = -1;

	try
	{
		const DWORD dwFileAttr = GetFileAttributes(str);

		if (dwFileAttr == DWORD(-1)) // file not found
		{
			iRet = -1;		// nothing
		} 
		else if (dwFileAttr & FILE_ATTRIBUTE_DIRECTORY)
		{
			iRet = 0;		//folder
		}
		else	
			iRet = 1;		// file
	}
	catch(...)
	{
	}

	return iRet;
}


the output of the function is different if i pass following string
C:\Windows\System32\speech\speechux\sapi.cpl,-5566


please help

What I have tried:

and my c# code is

public int CheckFileOrFolder(string str)
        {
            int iRet = -1;
            try
            {

                FileAttributes attr = System.IO.File.GetAttributes(str);
                //var files = Directory.GetFiles(@"c:\windows\system32\");

                if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
                {
                    iRet = 0;		//folder
                }
                else
                    iRet = 1;		// file
            }
            catch (Exception ex)
            {
                //File not found
                iRet = -1; // nothing
            }

            return iRet;
        }
Posted
Updated 31-Aug-17 4:47am
Comments
CPallini 31-Aug-17 5:06am    
What is the different output you get?
srilekhamenon 31-Aug-17 5:16am    
sorry i was sending wrong string in c++ code, now iam getting -1 in both case
Richard MacCutchan 31-Aug-17 6:59am    
When you catch an exception you should always print the details, including the message.

Your input isnt a valid path, but a path with the addition ",-5566". In that case the GetAttributes C function may return some value which doesnt work correct with the if/else code but System.IO.File.GetAttributes is correctly throwing an exception.

Use the debugger to look at the details to find the problem.
 
Share this answer
 
CheckFileOrFolder(@"C:\Windows\System32\speech\speechux\sapi.cpl");


return == 1 with c++ and C#
 
Share this answer
 
Hi ,

You can use this solution .

also you can use this IDE : Free Product Editions[^]

public int CheckFileOrFolder(string str)
{
			int iRet = -1;
			try
			{

				FileAttributes attr = System.IO.File.GetAttributes(str);
				//var files = Directory.GetFiles(@"c:\windows\system32\");

				if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
				{
					iRet = 0; //folder
				}
				else
				{
					iRet = 1; // file
				}
			}
			catch (Exception ex)
			{
				//File not found
				iRet = -1; 
			}

			return iRet;
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900