You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中使用文件选择器读取Windows连接FTP服务器TXT文件的问题

问题解决:UWP文件选择器读取FTP文件时Path为空导致崩溃

问题原因

FTP服务器上的文件属于远程资源,不在本地文件系统中。UWP的StorageFile.Path属性仅对本地文件有效,针对FTP这类远程文件会返回空值。而File.ReadAllLines方法依赖本地文件路径才能运行,传入空路径必然导致崩溃。

解决方案

放弃使用File.ReadAllLines,改用StorageFile自带的流读取API处理远程文件:

  • 调用StorageFile.OpenStreamForReadAsync()获取文件可读流
  • 通过StreamReader逐行读取文件内容

修改后的代码示例

public async void filepicker()
{
    Dictionary<string, Dictionary<string, HashSet<string>>> dayDic = new Dictionary<string, Dictionary<string, HashSet<string>>>();

    counterDic.Clear();
    dayDic.Clear();
    var filePicker = App.MainWindow.CreateOpenFilePicker();
    filePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
    filePicker.FileTypeFilter.Add(".log");
    filePicker.ViewMode = PickerViewMode.Thumbnail;
    var file = await filePicker.PickSingleFileAsync();

    if (file != null)
    {
        // 不再依赖file.Path,改用流读取远程文件
        using (var stream = await file.OpenStreamForReadAsync())
        using (var reader = new StreamReader(stream))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // 在这里处理每一行内容,替换原有逻辑
            }
        }
    }
}

补充说明

UWP文件选择器支持访问FTP、OneDrive等远程存储位置,但这些位置的文件无法通过传统System.IO.File类操作,必须使用StorageFile提供的异步API处理内容——因为这类文件不存在对应的本地文件路径。

内容的提问来源于stack exchange,提问作者Morris Van deursen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:22:15