为什么变量FileStream编写器为空?

为什么变量FileStream编写器为空?

问题描述:

我有两种情况使用作家。为什么变量FileStream编写器为空?

private void downloadFile(Int32 fileNr) 
     { 
      FileStream writer = null; 
      m_currentFileSize = 0; 
      fireEventFromBgw(Event.FileDownloadAttempting); 

      FileInfo file = this.Files[fileNr]; 
      FileInfo fileFirstDateTime = this.Files[0]; 
      FileInfo fileLastDateTime = this.Files[19]; 
      Int64 size = 0; 

      Byte[] readBytes = new Byte[this.PackageSize]; 
      Int32 currentPackageSize; 
      System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch(); 
      Int32 readings = 0; 
      Exception exc = null; 

      if (form1.checkBox1.Text == "Download satellite images") 
      { 
       LocalDirectorySettings(file, writer); 
      } 
      else 
      { 
       writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create); 
      } 


      HttpWebRequest webReq; 
      HttpWebResponse webResp = null; 

      try 
      { 
       webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path); 
       webResp = (HttpWebResponse)webReq.GetResponse(); 

       size = webResp.ContentLength; 
      } 
      catch (Exception ex) { exc = ex; } 

      m_currentFileSize = size; 
      fireEventFromBgw(Event.FileDownloadStarted); 

      if (exc != null) 
      { 
       bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc); 
      } 
      else 
      { 
       m_currentFileProgress = 0; 
       while (m_currentFileProgress < size && !bgwDownloader.CancellationPending) 
       { 
        while (this.IsPaused) { System.Threading.Thread.Sleep(100); } 

        speedTimer.Start(); 

        currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize); 

        m_currentFileProgress += currentPackageSize; 
        m_totalProgress += currentPackageSize; 
        fireEventFromBgw(Event.ProgressChanged); 
        try 
        { 
         writer.Write(readBytes, 0, currentPackageSize); 
        } 
        catch(Exception eee) 
        { 
         string myeee = eee.ToString(); 
        } 
        readings += 1; 

        if (readings >= this.StopWatchCyclesAmount) 
        { 
         m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000/(speedTimer.ElapsedMilliseconds + 1)); 
         speedTimer.Reset(); 
         readings = 0; 
        } 
       } 

       speedTimer.Stop(); 
       writer.Close(); 
       webResp.Close(); 
       if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); } 
      } 
      fireEventFromBgw(Event.FileDownloadStopped); 
     } 

当如果它的其他部分它的正常工作这一部分:

if (form1.checkBox1.Text == "Download satellite images") 
      { 
       LocalDirectorySettings(file, writer); 
      } 
      else 
      { 
       writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create); 
      } 

如果它做的是:它的罚款:

writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create); 

但是,一旦我改变复选框和它的IF的第一部分:

LocalDirectorySettings(file, writer); 

这是LocalDirectorySettings方法代码:

public void LocalDirectorySettings(FileInfo file, FileStream writer) 
     { 
      try 
      { 
       var startIndex = file.Path.IndexOf("region=") + "region=".Length; 
       var length = file.Path.IndexOf("&", startIndex) - startIndex; 
       var code = file.Path.Substring(startIndex, length); 
       var countryName = form1.codeToFullNameMap[code]; 

       string firstDT = ParseDateTime(this.Files[0]); 
       string lastDT = ParseDateTime(this.Files[19]); 
       string subDirectoryDT = firstDT + "---" + lastDT; 

       string countryPath = Path.Combine(form1.mainPath, countryName); 
       LocalDirectory = countryPath + "\\" + subDirectoryDT; 

       if (!Directory.Exists(LocalDirectory)) 
       { 
        Directory.CreateDirectory(LocalDirectory); 
       } 

       string fileName = this.LocalDirectory + "\\" + "test.png"; //file.Name + "---" + countFilesNames++.ToString("D6") + ".png"; 
       writer = new FileStream(fileName, System.IO.FileMode.Create); // Set a breakpoint here. 
      } 
      catch (Exception err) 
      { 
       string ggg = err.ToString(); 
      } 
     } 

即使有与LocalDirectorySettings方法内文学家的实例行:

writer = new FileStream(fileName, System.IO.FileMode.Create); 

而且我用一个破发点和它得到这条线在LocalDirectorySettings但是当它继续执行部分:

try 
        { 
         writer.Write(readBytes, 0, currentPackageSize); 
        } 
        catch(Exception eee) 
        { 
         string myeee = eee.ToString(); 
        } 

它变得到catch部分说writer为null。并使用一个断点,我看到作家是空的。

为什么当它到达LocalDirectorySettings时,写入器在它之后为空?

设置参数,在LocalDirectorySettings()方法命名writer一个局部变量,对其他局部变量没有效果,也叫writer,在主叫方,downloadFile()发现。

我强烈建议反对使用类字段共享此对象(如在其他答案中所建议的)。没有理由,而这样做会让你的班级变得混乱。相反,要么通过引用传递参数,要么更好,只需要LocalDirectorySettings()方法返回对象。例如:

void downloadFile(int fileNr) 
{ 
    FileStream writer; 

    //... 

    if (form1.checkBox1.Text == "Download satellite images") 
    { 
     writer = LocalDirectorySettings(file); 
    } 
    else 
    { 
     writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create); 
    } 

    //... 
} 

public FileStream LocalDirectorySettings(FileInfo file) 
{ 
    try 
    { 
     //... 

     string fileName = this.LocalDirectory + "\\" + "test.png"; //file.Name + "---" + countFilesNames++.ToString("D6") + ".png"; 
     return new FileStream(fileName, System.IO.FileMode.Create); 
    } 
    catch (Exception err) 
    { 
     string ggg = err.ToString(); 
     throw; // you don't actually handle the exception, so rethrowing 
       // is the appropriate action here. Your only alternative 
       // would be to return "null" and have the caller check for 
       // that return value explicitly. 
    } 
} 

LocalDirectorySettings中,您正在为函数参数分配新的FileStream。这不影响downloadFile中的作者变量。

使writer成为一个成员变量,因此这两种方法可以共享它。

FileStream writer = null; 
private void downloadFile(Int32 fileNr) 
{ 
    // Do stuff with writer 
} 

public void LocalDirectorySettings(FileInfo file) 
{ 
    // Do stuff with writer 
}