Hi...
How do I know wich is the current folder of an App?? I mean... Is there a way to know where is the exe located from the running code?
thanks in advance
Hi...
How do I know wich is the current folder of an App?? I mean... Is there a way to know where is the exe located from the running code?
thanks in advance
Windows Mobile doesn't have the concept of a current folder. The "current folder" is basically always set to be the root of the filesystem, no matter where your application is located.
To get the path your application is located, you can use Assembly.GetExecutingAssembly()
, and the CodeBase
property or GetName()
method
Don't fight the system.
Microsoft does not want you to use the program files folder for anything other then assemblies. Config files should go in Application Data, Save files and the like which users need to know about go in My Documents.
jalf's answer will work but you are fighting the system. Unless their is a really good reason why you want to know what folder your assembly is in then I would suggest against it.
You can use GetModuleFileName
In the below sample, the method GetExecutablePath returns the location of the exe, and GetStartupPath returns the directory of the exe.
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
[DllImport("coredll", SetLastError = true)]
public static extern uint GetModuleFileName(IntPtr hModule, StringBuilder lpFilename, [MarshalAs(UnmanagedType.U4)] int nSize);
[DllImport("coredll")]
public static extern uint FormatMessage([MarshalAs(UnmanagedType.U4)] FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, uint dwLanguageId, out IntPtr lpBuffer, uint nSize, IntPtr Arguments);
[DllImport("coredll")]
public static extern IntPtr LocalFree(IntPtr hMem);
[Flags]
internal enum FormatMessageFlags : uint
{
AllocateBuffer = 256,
FromSystem = 4096,
IgnoreInserts = 512
}
public static string GetModuleFileName(IntPtr hModule)
{
StringBuilder lpFilename = new StringBuilder(short.MaxValue);
uint num = GetModuleFileName(hModule, lpFilename, lpFilename.Capacity);
if (num == 0)
{
throw CreateWin32Exception(Marshal.GetLastWin32Error());
}
return lpFilename.ToString();
}
private static Win32Exception CreateWin32Exception(int error)
{
IntPtr buffer = IntPtr.Zero;
try
{
if (FormatMessage(FormatMessageFlags.IgnoreInserts | FormatMessageFlags.FromSystem | FormatMessageFlags.AllocateBuffer, IntPtr.Zero, (uint)error, 0, out buffer, 0, IntPtr.Zero) == 0)
{
return new Win32Exception();
}
return new Win32Exception(error, Marshal.PtrToStringUni(buffer));
}
finally
{
if (buffer != IntPtr.Zero)
{
LocalFree(buffer);
}
}
}
public static string GetStartupPath()
{
return Path.GetDirectoryName(GetExecutablePath());
}
public static string GetExecutablePath()
{
return GetModuleFileName(IntPtr.Zero);
}
}
string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;
fullAppPath = Path.GetDirectoryName(fullAppName);