文件同步连续使用两次 [英] File used twice in a row synchronously

查看:104
本文介绍了文件同步连续使用两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序首次启动时,我在隔离存储中创建一个文本文件

 isoStore.CreateFile(  MyApp \\ Memo.txt); 



和启动时我这样做(memoPrices是一个List< string>,它保留了一些价格):

  public   static   async   void  FillPricesFromIsoStore()
{
使用(IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if ( isoStore.FileExists( MarketApp\\Memo.txt))
{
尝试
{
IsolatedStorageFileStream fileStr eam = new IsolatedStorageFileStream( MarketApp \\ Memo .txt,FileMode.Open,isoStore);
使用(StreamReader file = new StreamReader(fileStream))
{
字符串 input = await file.ReadLineAsync();
while (输入!= null
{
memoPrices。添加(输入);
input = await file.ReadLineAsync();
}
file.Close();
}
}
catch (例外e)
{
// 我添加了这个,因为e.InnerException不返回任何内容
System.Diagnostics.Debug.WriteLine(e.ToString ());
}
}
}
}



在应用程序的第一次启动时,我发现一个异常,说我不能使用该文件,因为它在其他地方使用,该地方是创建它的地方。

这是catch块的输出:

 System.IO.IsolatedStorage.IsolatedStorageException:IsolatedStorageFileStream上不允许操作。 
在System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor( String 路径,FileMode模式,FileAccess访问,FileShare共享, Int32 bufferSize,IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor( String path,FileMode mode,IsolatedStorageFile isf )
在MarketApp.ShortTimeStoring。< FillPricesFromIsoStore> d__0.MoveNext()





我尝试过:



我试图反复调用该方法,直到该文件可用。

解决方案

IsolatedStorageFile.CreateFile方法 [ ^ ]返回 IsolatedStorageFileStream 。您没有显示代码的相关部分,但我怀疑您忘记关闭/处理该流,这意味着该文件仍处于打开状态。



更改完成后创建文件以关闭流的代码:

 使用(< span class =code-keyword> var  stream = isoStore.CreateFile(  MyApp \\ Memo.txt))
{
// 在此初始化文件内容...
}



您还应该更改 FillPricesFromIsoStore 方法来包装使用块中的流:

 使用 var  fileStream = isoStore.OpenFile(  MarketApp \ \ Memo.txt,FileMod e.Open))
使用(StreamReader file = new StreamReader(fileStream))
{
...
}


它与Visual Studio 2013或任何特定的IDE无关。这是.NET的基本功能。它可能不会太强烈说如果你不使用它,你就无处可去。



所有你需要的是:

异常类(系统) [< a href =https://msdn.microsoft.com/en-us/library/system.exception%28v=vs.110%29.aspxtarget =_ blanktitle =New Window> ^ ],

异常。 InnerException属性(系统) [ ^ ]。



在调试过程中,您可以随时插入一些捕获异常的调试代码并尝试检查由它引用的内部异常,依此类推,递归。此外,此信息将添加到 Exception.ToString()结果中。另请注意RyanDev的评论。当然,根本不做任何编程,你必须清楚地了解异常如何工作以及如何使用它们。 (如果不是你最后两个问题所揭示的混乱心态,我不会质疑你对此事的了解。)对于一个非常简短的介绍,我可以提供我过去的答案:

C#构造函数中的异常导致调用者分配失败吗? [ ^ ],

在操作系统中存储了.net异常 [ ^ ],

图片采取来自网络摄像头没有保存在服务器上 [ ^ ]。



-SA

In my application at first start I create a text file in isolated storage

isoStore.CreateFile("MyApp\\Memo.txt");


and at launching I do this (memoPrices is a List<string> that keeps some prices):

public static async void FillPricesFromIsoStore()
{
    using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (isoStore.FileExists("MarketApp\\Memo.txt"))
        {
            try
            {
                IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("MarketApp\\Memo.txt", FileMode.Open, isoStore);
                using (StreamReader file = new StreamReader(fileStream))
                {
                    String input = await file.ReadLineAsync();
                    while (input != null)
                    {
                        memoPrices.Add(input);
                        input = await file.ReadLineAsync();
                    }
                    file.Close();
                }
            }
            catch(Exception e)
            {
                // I added just this because e.InnerException doesn't return anything
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }
        }
    }
}


At the first start of the app I catch an exception that says that I can't use the file because it is used in other place, that place is where it is created.
This is the output of the catch block:

System.IO.IsolatedStorage.IsolatedStorageException: Operation not permitted on IsolatedStorageFileStream.
   at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, IsolatedStorageFile isf)
   at System.IO.IsolatedStorage.IsolatedStorageFileStream..ctor(String path, FileMode mode, IsolatedStorageFile isf)
   at MarketApp.ShortTimeStoring.<FillPricesFromIsoStore>d__0.MoveNext()



What I have tried:

I tried to call the method repeatedly until the file is usable.

解决方案

The IsolatedStorageFile.CreateFile method[^] returns an IsolatedStorageFileStream. You haven't shown the relevant parts of your code, but I suspect you forgot to close / dispose that stream, which means the file is still open.

Change the code that creates the file to close the stream when you're finished with it:

using (var stream = isoStore.CreateFile("MyApp\\Memo.txt"))
{
    // Initialize the file contents here...
}


You should also change the FillPricesFromIsoStore method to wrap the stream in a using block:

using (var fileStream = isoStore.OpenFile("MarketApp\\Memo.txt", FileMode.Open))
using (StreamReader file = new StreamReader(fileStream))
{
    ...
}


It has nothing to do with Visual Studio 2013 or any particular IDE. This is a fundamental feature of .NET. It probably won't be too strong saying that if you don't use it, you are going nowhere.

All you need is this:
Exception Class (System)[^],
Exception.InnerException Property (System)[^].

During debugging, you can always insert some debug code which catches your exception and tries to examine the inner exception referenced by it, and so on, recursively. Moreover, this information is added to Exception.ToString() result. Note also the comment by RyanDev. Of course, do do any programming at all, you have to clearly understand how exceptions work and how they can be used. (If not your confused state of mind revealed by your last two questions, I would not question your knowlege of this matter.) For a really short introduction, I can offer my past answers:
Does Exception in C# Constructor Cause Caller Assignment to Fail?[^],
where was stored .net exceptions in operating system[^],
Image taken from Webcam not getting saved on the server[^].

—SA


这篇关于文件同步连续使用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆