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

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条回答 默认 最新

  • CSDN专家-showbo 2021-08-21 13:06
    关注

    Directory.GetFiles设置搜索目录下的所有xml文件就行。有帮助麻烦点个采纳【本回答右上角】,谢谢~~

    img

    
    string[] xmlfiles = System.IO.Directory.GetFiles(@"F:\CSharp", "*.xml", SearchOption.AllDirectories);
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

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

悬赏问题

  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”