qin
2024-09-28 e358beb08f5be49703009b64f058ecfbcfeefbd9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using Autodesk.Revit.DB;
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Shapes;
 
namespace HStation.RevitDev.RevitDataExport.Utility
{
    public class VersionUtil
    {
        private const string MatchVersion = @"((?<=Autodesk Revit |Format: )20\d{2})";
 
        public static string GetVersion(string filePath)
        {
            BasicFileInfo fileInfo = BasicFileInfo.Extract(filePath);//引入Autodesk.Revit.DB.BasicFileInfo
            string version = fileInfo.Format;
            if (!string.IsNullOrEmpty(version)) { return version; }
 
            try
            {
                Encoding useEncoding = Encoding.Unicode;
                var temp = System.IO.Path.Combine(System.IO.Path.GetTempPath(), new Guid().ToString() + ".rfa");
                File.Copy(filePath, temp, true);
                using (FileStream file = new FileStream(temp, FileMode.Open))
                {
                    //匹配字符有20个(最长的匹配字符串18版本的有20个),为了防止分割对匹配造成的影响,需要验证20次偏移结果
                    for (int i = 0; i < 20; i++)
                    {
                        byte[] buffer = new byte[2000];
                        file.Seek(i, SeekOrigin.Begin);
                        while (file.Read(buffer, 0, buffer.Length) != 0)
                        {
                            var head = useEncoding.GetString(buffer);
                            Regex regex = new Regex(MatchVersion);
                            var match = regex.Match(head);
                            if (match.Success)
                            {
                                version = match.ToString();
                                return version;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return null;
            }
            return version;
        }
    }
}