如何打开一个文件并在TextBlock中显示它
本文关键字:TextBlock 显示 文件 一个 何打开 | 更新日期: 2023-09-27 18:07:05
所以我几乎只是从c#开始,我只是试图从。txt文件中获取文本,并在我的应用程序上显示它。我试过在任何地方寻找我能想到的,但我只发现人们这样做的控制台应用程序,当我尝试应用相同的解决方案,我只会给出错误。这就是我现在想要使用的,但我只是不断得到错误:"无法将'字符串'转换为'System.IO。为StreamReader(path)之后的路径设置流' ' '。我试过它作为一个控制台应用程序(改变输出代码)和工作良好
namespace FileOpenApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void inputSubmitButton_Click(object sender, RoutedEventArgs e)
{
outputBox.Text = "Testing";
processFile();
}
private void processFile()
{
try
{
string path = @"C:'Users'Fabian'Dropbox'test.txt";
using (StreamReader sr = new StreamReader(path)) //errors here
{
string line;
while ((line = sr.ReadLine()) != null)
{
outputBox.Text = line;
currentProcess.Text = "Done";
}
}
}
catch (Exception e)
{
currentProcess.Text = "Something went wrong";
}
}
}
}
编辑:试图使用这个代码,我得到的错误,文件不存在于命名空间系统。IO
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace FileOpenApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void inputSubmitButton_Click(object sender, RoutedEventArgs e)
{
outputBox.Text = "Testing";
processFile();
}
private void processFile()
{
string path = @"C:'Users'Fabian'Dropbox'test.txt";
string contents = "";
System.IO.File.ReadAllText(path, contents);
outputBox.Text = contents;
}
}
}
也试过;
string path = @"C:'Users'Fabian'Dropbox'test.txt";
outputBox.Text = File.ReadAllText(path);
您应该调用File.ReadAllText()
,它为您完成所有这些工作并返回一个字符串。