Created
September 26, 2014 14:01
-
-
Save hounsell/7e3d29019dadfd05359d to your computer and use it in GitHub Desktop.
Get Language Id for File (Part 1)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Security.Permissions; | |
using System.Text; | |
using System.Threading.Tasks; | |
using System.Runtime.InteropServices; | |
namespace VersionInfo | |
{ | |
public class RealVersionInfo | |
{ | |
public string FileName { get; set; } | |
public int LanguageId { get; set; } | |
private RealVersionInfo(string filename) | |
{ | |
FileName = filename; | |
} | |
public unsafe static RealVersionInfo GetVersionInformation(string filename) | |
{ | |
if(!File.Exists(filename)) | |
{ | |
// Check for read access - exists errors if can't be read, but below will only throw an error when access fails, but file exists | |
new FileIOPermission(FileIOPermissionAccess.Read, Path.GetFullPath(filename)).Demand(); | |
throw new FileNotFoundException(filename); | |
} | |
int handle; | |
int infoSize = NativeMethods.GetFileVersionInfoSize(filename, out handle); | |
RealVersionInfo rvi = new RealVersionInfo(filename); | |
if(infoSize != 0) | |
{ | |
byte[] mem = new byte[infoSize]; | |
fixed(byte* memPtr = mem) | |
{ | |
IntPtr memIntPtr = new IntPtr((void*)memPtr); | |
bool success = NativeMethods.GetFileVersionInfo(filename, 0, infoSize, new HandleRef(null, memIntPtr)); | |
if (success) | |
{ | |
rvi.LanguageId = GetVarEntry(memIntPtr); | |
} | |
} | |
} | |
return rvi; | |
} | |
private static int GetVarEntry(IntPtr memPtr) | |
{ | |
IntPtr memRef = IntPtr.Zero; | |
int memLen; | |
if (NativeMethods.VerQueryValue(new HandleRef(null, memPtr), "\\VarFileInfo\\Translation", ref memRef, out memLen)) | |
{ | |
return (Marshal.ReadInt16(memRef) << 16) + Marshal.ReadInt16((IntPtr)((long)memRef + 2)); | |
} | |
return 0x040904E4; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment