Lukas00990 2021-08-21 01:19 采纳率: 42.1%
浏览 121
已结题

C#遍历文件夹读取.xml文件

目前已有代码实现的功能是,在指定文件夹指定.xml中。用GUI 里的键选取指定.xml文件,可以在TIA PORTAL 里生成对应的数据块。因为如果有多个.XML文件,需要读取多次才能达到效果,比较麻烦,现在想实现的功能是,用GUI 的键选取指定文件夹,然后代码自动遍历文件夹中所有的.xml文件,然后生成对应数据块。附上现有的一部分代码。其中importitem 和 importstructure两个方法代表现阶段如何导入

using System;
using System.Collections.Generic;
using System.IO;
using Siemens.Engineering;
using Siemens.Engineering.Hmi;
using Siemens.Engineering.Hmi.Communication;
using Siemens.Engineering.Hmi.Cycle;
using Siemens.Engineering.Hmi.Globalization;
using Siemens.Engineering.Hmi.RuntimeScripting;
using Siemens.Engineering.Hmi.Screen;
using Siemens.Engineering.Hmi.Tag;
using Siemens.Engineering.Hmi.TextGraphicList;
using Siemens.Engineering.SW;
using Siemens.Engineering.SW.Blocks;
using Siemens.Engineering.SW.ExternalSources;
using Siemens.Engineering.SW.Tags;
using Siemens.Engineering.SW.Types;
using Siemens.Engineering.Cax;
using Siemens.Engineering.SW.WatchAndForceTables;

namespace TiaOpennessHelper
{
    public partial class OpennessHelper
    {
        /// <summary>
        /// Imports a file under the given TIA object with the given import options
        /// </summary>
        /// <param name="destination">TIA object under which the file will be imported.</param>
        /// <param name="filePath">Path to the file</param>
        /// <param name="importOption">TIA import options</param>
        /// <exception cref="System.ArgumentNullException">Parameter is null;destination</exception>
        /// <exception cref="System.ArgumentException">Parameter is null or empty;filePath</exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="System.UnauthorizedAccessException"></exception>
        /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
        public static void ImportItem(IEngineeringCompositionOrObject destination, string filePath, ImportOptions importOption)
        {
            if (destination == null)
                throw new ArgumentNullException(nameof(destination), "Parameter is null");
            if (string.IsNullOrEmpty(filePath))
                throw new ArgumentException("Parameter is null or empty", nameof(filePath));

            var fileInfo = new FileInfo(filePath);
            filePath = fileInfo.FullName;


            if (destination is CycleComposition || destination is ConnectionComposition || destination is MultiLingualGraphicComposition
                || destination is GraphicListComposition || destination is TextListComposition)
            {
                var parameter = new Dictionary<Type, object>();
                parameter.Add(typeof(string), filePath);
                parameter.Add(typeof(ImportOptions), importOption);
                // Export prüfen
                (destination as IEngineeringComposition).Invoke("Import", parameter);
            }
            else if (destination is PlcBlockGroup)
            {
                if (Path.GetExtension(filePath).Equals(".xml"))
                    (destination as PlcBlockGroup).Blocks.Import(fileInfo, importOption);
                else
                {
                    var currentDestination = destination as IEngineeringObject;
                    while (!(currentDestination is PlcSoftware))
                    {
                        currentDestination = currentDestination.Parent;
                    }
                    var col = (currentDestination as PlcSoftware).ExternalSourceGroup.ExternalSources;

                    var sourceName = Path.GetRandomFileName();
                    sourceName = Path.ChangeExtension(sourceName, ".src");
                    var src = col.CreateFromFile(sourceName, filePath);
                    src.GenerateBlocksFromSource();
                    src.Delete();
                }
            }
            else if (destination is PlcTagTableGroup)
                (destination as PlcTagTableGroup).TagTables.Import(fileInfo, importOption);
            else if (destination is PlcWatchAndForceTableGroup)
                (destination as PlcWatchAndForceTableGroup).WatchTables.Import(fileInfo, importOption);
            else if (destination is PlcTypeGroup)
                (destination as PlcTypeGroup).Types.Import(fileInfo, importOption);
            else if (destination is PlcExternalSourceGroup)
            {
                var temp = (destination as PlcExternalSourceGroup).ExternalSources.Find(Path.GetFileName(filePath));
                if (temp != null)
                    temp.Delete();
                (destination as PlcExternalSourceGroup).ExternalSources.CreateFromFile(Path.GetFileName(filePath), filePath);
            }
            else if (destination is TagFolder)
                (destination as TagFolder).TagTables.Import(fileInfo, importOption);
            else if (destination is ScreenFolder)
                (destination as ScreenFolder).Screens.Import(fileInfo, importOption);
            else if (destination is ScreenTemplateFolder)
                (destination as ScreenTemplateFolder).ScreenTemplates.Import(fileInfo, importOption);
            else if (destination is ScreenPopupFolder)
                (destination as ScreenPopupFolder).ScreenPopups.Import(fileInfo, importOption);
            else if (destination is ScreenSlideinSystemFolder)
                (destination as ScreenSlideinSystemFolder).ScreenSlideins.Import(fileInfo, importOption);
            else if (destination is VBScriptFolder)
                (destination as VBScriptFolder).VBScripts.Import(fileInfo, importOption);
            else if (destination is ScreenGlobalElements)
                (destination.Parent as HmiTarget)?.ImportScreenGlobalElements(fileInfo, importOption);
            else if (destination is ScreenOverview)
                (destination.Parent as HmiTarget)?.ImportScreenOverview(fileInfo, importOption);
            else
            {
                Console.WriteLine("Not work");
            }

        }

        /// <summary>Imports a folder structure into the given destination</summary>
        /// <param name="targetLocation">TIA object under which the structure will be imported</param>
        /// <param name="folderPath">Path to the folder to import</param>
        /// <param name="importOption">TIA import options</param>
        /// <exception cref="System.ArgumentNullException">Parameter is null;targetLocation</exception>
        /// <exception cref="System.ArgumentException">Parameter is null or empty;folderPath</exception>
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="System.UnauthorizedAccessException"></exception>
        /// <exception cref="System.IO.DirectoryNotFoundException"></exception>
        // ReSharper disable once UnusedMember.Local
        private static void ImportStructure(IEngineeringObject targetLocation, string folderPath, ImportOptions importOption)
        {
            if (targetLocation == null)
                throw new ArgumentNullException(nameof(targetLocation), "Parameter is null");
            if (string.IsNullOrEmpty(folderPath))
                throw new ArgumentException("Parameter is null or empty", nameof(folderPath));

            var files = Directory.GetFiles(folderPath);
            var dirs = Directory.GetDirectories(folderPath);

            foreach (var file in files)
            {
                ImportItem(targetLocation, file, importOption);
            }

            foreach (var dir in dirs)
            {
                var subDir = GetFolderByName(targetLocation, Path.GetFileName(dir));
                ImportStructure(subDir as IEngineeringObject, dir, importOption);
            }
        }

        public static bool CaxImport(Project project, string filePath, ImportCaxOptions importOptions)
        {
            if (project == null)
                throw new ArgumentNullException(nameof(project), "Parameter is null");
            if (String.IsNullOrEmpty(filePath))
                throw new ArgumentException("Parameter is null or empty", nameof(filePath));

            var provider = project.GetService<CaxProvider>();
            if (provider == null) return false;
            var logPath = new FileInfo(Path.Combine(Path.GetDirectoryName(filePath), "Import.log"));

            CaxImportOptions tmpOptions;

            if (Enum.TryParse(importOptions.ToString(), out tmpOptions))
                return provider.Import(new FileInfo(filePath), logPath, tmpOptions);

            return provider.Import(new FileInfo(filePath), logPath, CaxImportOptions.MoveToParkingLot);

        }
    }
}


  • 写回答

2条回答

      报告相同问题?

      相关推荐 更多相似问题

      问题事件

      • 系统已结题 8月31日
      • 已采纳回答 8月23日
      • 赞助了问题酬金 8月21日
      • 修改了问题 8月21日
      • 展开全部

      悬赏问题

      • ¥15 有关时间计算器的问题
      • ¥200 Chrome浏览器自动保存密码需要解密!来人
      • ¥18 关于#c语言#的问题:如何把下面几个代码放在一起编序号,然后输入对应数字运行对应代码,还可以返回重输
      • ¥30 windows下无法运行go test的问题
      • ¥15 多个Rigify骨骼 导入一起 后 没有 控制器面板
      • ¥15 想问一下sprak ada语言的pre和post怎么设
      • ¥15 使用python将分子模拟输出.gro文件
      • ¥15 港诡实录的背包系统拆解
      • ¥15 宽带IP网络路由器的初始路由表和最终路由表
      • ¥15 c语言基础这几个该怎么搞