MAUI实战 - MAUI基础 - MAUI基础练习
MAUI App可用于存储数据的目录
要获取可用于MAUI的APP存取数据的目录,可以使用MAUI的FileSystem类,位于命名空间Microsoft.Maui.Storage下,通过FileSystem.AppDataDirectory可获取用于储存app数据的目录

先看步骤和代码,文后附有安卓系统实际运行效果图。

练习步骤如下:
1、使用Visual Studio 2022创建MAUI项目(HtCurrentDirectory)

2、编辑项目文件,把applicationId修改为com.hovertree.htcurrentdirectory

3、编辑MainPage.xml文件,代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="HtCurrentDirectory.MainPage">

<ScrollView>
<VerticalStackLayout
Spacing="25"
Padding="30,0"
VerticalOptions="Center">

<Image
Source="https://hovertree.com/hvtimg/201512/agagq0or.jpg"
SemanticProperties.Description="hovertree.com!"
HeightRequest="200"
HorizontalOptions="Center" />

<Label x:Name="HtCachePath"
Text="Hello, Hovertree!"
SemanticProperties.HeadingLevel="Level1"
FontSize="32"
HorizontalOptions="Center" />

<Label x:Name="htFile"
HorizontalOptions="Center" />

<Label
x:Name="HtLabel"
Text="Welcome to Hovertree MAUI "
SemanticProperties.HeadingLevel="Level2"
SemanticProperties.Description="Welcome to Hovertree MAUI"
FontSize="18"
HorizontalOptions="Center" />

<Button
x:Name="HtBtn"
Text="Click me"
SemanticProperties.Hint="Cuttent "
Clicked="OnHtBtnClicked"
HorizontalOptions="Center" />

</VerticalStackLayout>
</ScrollView>

</ContentPage>
编辑MainPage.xml.cs文件,代码如下:
/* MAUI 创建文本文件,写入文本
by 何问起
*/
namespace HtCurrentDirectory;

public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

private async void OnHtBtnClicked(object sender, EventArgs e)
{
string m_appDataPath = FileSystem.AppDataDirectory;
HtLabel.Text = m_appDataPath;
HtCachePath.Text = FileSystem.CacheDirectory;
string m_fileName = m_appDataPath + "/hovertree.txt";
htFile.Text = m_fileName;
if ( File.Exists(m_fileName))
{
await DisplayAlert("Hovertree Tips", File.ReadAllText(m_fileName), "OK");
}
else
{
File.WriteAllText(m_fileName, "何问起 首页: https://hovertree.com/", System.Text.Encoding.UTF8);//创建文件,并写入文本,如果文件已存在,则覆盖
}
}
}
安卓系统第一次点击按钮效果:

后续点击按钮会弹出对话框:
收藏 列表

评论:
  • 2023-08-23 16:58 Maui读取U盘文件的例子有没有啊