如何从项目文件夹中读取文件?

时间:2011-06-30 08:22:02

标签: windows-phone-7

当我的应用程序第一次在Windows手机上启动时,我想从项目文件夹中获取一些文件(xml / images)并将它们写入隔离存储。

如何首次检测到我的应用正在运行?

如何访问项目文件夹中的文件?

2 个答案:

答案 0 :(得分:9)

这是从visual studio项目中读取文件的另一种方法。以下显示了如何读取txt文件,但也可以用于其他文件。这里的文件与.xaml.cs文件位于同一目录中。

var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();

确保您的文件被标记为内容。

答案 1 :(得分:1)

如果您指的是Visual Studio项目文件夹中的项目文件夹,我通常会右键单击文件并将构建操作设置为“嵌入式资源”。在运行时,您可以从嵌入式资源中读取数据,如下所示:

// The resource name will correspond to the namespace and path in the file system.
// Have a look at the resources collection in the debugger to figure out the name.
string resourcePath = "assembly namespace" + "path inside project";
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resources = assembly .GetManifestResourceNames();
List<string> files = new List<string>();

if (resource.StartsWith(resourcePath))
{
    StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource), Encoding.Default);
    files.Add(reader.ReadToEnd());
}

要阅读图像,您需要这样的内容来阅读信息流:

    public static byte[] ReadAllBytes(Stream input)
    {
        byte[] buffer = new byte[32 * 1024];

        using (MemoryStream ms = new MemoryStream())
        {
            int read;

            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }

            return ms.ToArray();
        }
    }
相关问题