简体   繁体   English

写完后读取文件

[英]Reading file after writing it

I have a strange problem. 我有一个奇怪的问题。 So my code follows as following. 所以我的代码如下。

  1. The exe takes some data from the user exe从用户那里获取一些数据

  2. Call a web service to write(and create CSV for the data) the file at perticular network location(say \\some-server\\some-directory). 调用Web服务在特定网络位置(例如\\ some-server \\ some-directory)写入文件(并为数据创建CSV)。 Although this web service is hosted at the same location where this folder is (ie i can also change it to be c:\\some-directory). 虽然此Web服务托管在此文件夹所在的同一位置(即我也可以将其更改为c:\\ some-directory)。 It then returns after writing the file 然后在写入文件后返回

  3. the exe checks for the file to exists, if the file exists then further processing else quite with error. exe检查文件是否存在,如果文件存在则进一步处理其他错误。

The problem I am having is at step 3. When I try to read the file immediately after it has been written, I always get file not found exception(but the file there is present). 我遇到的问题是在第3步。当我尝试在文件写入后立即读取文件时,我总是得到文件未找到异常(但文件存在)。 I do not get this exception when I am debugging (because then I am putting a delay by debugging the code) or when Thread.Sleep(3000) before reading the file. 我在调试时没有得到这个异常(因为那时我通过调试代码来延迟)或者在读取文件之前的Thread.Sleep(3000)

This is really strange because I close the StreamWriter before I return the call to exe. 这真的很奇怪,因为我在返回对exe的调用之前关闭了StreamWriter Now according to the documention, close should force the flush of the stream. 现在根据文档,close应强制刷新流。 This is also not related to the size of the file. 这也与文件的大小无关。 Also I am not doing Async thread calls for writing and reading the file. 此外,我没有进行异步线程调用来写入和读取文件。 They are running in same thread serially one after another(only writing is done by a web service and reading is done by exe. Still the call is serial) 它们一个接一个地串行运行在同一个线程中(只有写入由Web服务完成,读取由exe完成。仍然是调用串行)

I do not know, but it feels like there is some time difference between the file actually gets written on the disk and when you do Close() . 我不知道,但感觉文件实际写在磁盘上和你做Close()时有一些时间差异。 However this baffling because this is not at all related to size. 然而这令人困惑,因为这与尺寸无关。 This happens for all file size. 这适用于所有文件大小。 I have tried this with file with 10, 50, 100,200 lines of data. 我试过这个带有10,50,100,200行数据的文件。

Another thing which I suspected was since I was writing this file to a network location, it could be windows is optimizing the call by writing first to cache and then to network location. 我怀疑的另一件事是,因为我将此文件写入网络位置,可能是Windows通过首先写入缓存然后写入网络位置来优化调用。 So I went ahead and changed the code to write it on drive(ie use c:\\some-directory), rather than network location. 所以我继续改变代码将其写入驱动器(即使用c:\\​​ some-directory),而不是网络位置。 But it also resulted in same error. 但它也导致了同样的错误。

There is no error in code(for reading and writing). 代码中没有错误(用于读写)。 As explained earlier, by putting a delay, it starts working fine. 如前所述,通过延迟,它开始正常工作。 Some other useful information 一些其他有用的信息

  1. The exe is .Net Framework 3.5 该exe是.Net Framework 3.5
  2. Windows Server 2008(64 bit, 4 GB Ram) Windows Server 2008(64位,4 GB Ram)

Edit 1 File.AppendAllText() is not correct solution, as it creates a new file, if it does not exits 编辑1 File.AppendAllText()是不正确的解决方案,因为它创建一个新文件,如果它不退出

Edit 2 code for writing 编辑2代码进行编写

using (FileStream fs = new FileStream(outFileName, FileMode.Create))
        {
            using (StreamWriter writer = new StreamWriter(fs, Encoding.Unicode))
            {
                writer.WriteLine(someString)
            }
        }

code for reading 阅读代码

  StreamReader rdr = new StreamReader(File.OpenRead(CsvFilePath));
  string header = rdr.ReadLine();
  rdr.Close();

Edit 3 used textwriter, same error 编辑3使用的文本编写器,相同的错误

  using (TextWriter writer = File.CreateText(outFileName))
    {
    }

Edit 3 Finally as suggested by some users, I am doing a check for the file in while loop for certain number of times before I throw the exception of file not found. 编辑3最后,正如一些用户所建议的那样,在抛出未找到文件的异常之前,我正在检查while循环中的文件一定次数。

int i = 1;
while (i++ < 10)
{
   bool fileExists = File.Exists(CsvFilePath);
   if (!fileExists)
     System.Threading.Thread.Sleep(500);
   else
     break;
}

So you are writing a stream to a file, then reading the file back to a stream? 所以你正在写一个文件流,然后将文件读回流? Do you need to write the file then post process it, or can you not just use the source stream directly? 您是否需要编写文件然后对其进行处理,或者您是否可以直接使用源流?

If you need the file, I would use a loop that keeps checking if the file exists every second until it appears (or a silly amount of time has passed) - the writer would give you an error if you couldn't write the file, so you know it will turn up eventually. 如果你需要这个文件,我会使用一个循环来检查文件是否每秒都存在直到它出现(或者经过了一段时间) - 如果你不能写文件,编写器会给你一个错误,所以你知道它最终会出现。

Since you're writing over a network, most optimal solution would be to save your file in the local system first, then copy it to network location. 由于您是通过网络编写的,因此最佳解决方案是首先将文件保存在本地系统中,然后将其复制到网络位置。 This way you can avoid network connection problems. 这样可以避免网络连接问题。 And as well have a backup in case of network failure. 并且在网络故障的情况下也有备份。

Based on your update, Try this instead: 根据您的更新,请尝试此操作:

File.WriteAllText(outFileName, someString);
header = null;
using(StreamReader reader = new StreamReader(CsvFilePath)) {
    header = reader.ReadLine();
}

Have you tried to read after disposing the writer FileStream? 处理完作者FileStream后你试过读过吗?

Like this: 像这样:

using (FileStream fs = new FileStream(outFileName, FileMode.Create))
{
    using (StreamWriter writer = new StreamWriter(fs, Encoding.Unicode))
    {
        writer.WriteLine(someString)
    }
}

using (StreamReader rdr = new StreamReader(File.OpenRead(CsvFilePath)))
{
    string header = rdr.ReadLine();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM