简体   繁体   中英

Object reference not set to an instance of an object using ( READTOEND)

I have the following code to download the txt file using ftp and write back to another file.

 ftp = (FtpWebRequest)WebRequest.Create("ftp://" + ftpHost + ftpDIR + "/SAPValidObjects.txt");
 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
 ftp.UseBinary = false;
 ftp.Credentials = new NetworkCredential(ftpUserID, ftpPWD);
 FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
 Stream sResponse = response.GetResponseStream();
 StreamReader srSAPCostObjects = new StreamReader(sResponse);
 m_swSAPCostCentres.Write(srSAPCostObjects.ReadToEnd());
 m_swSAPCostCentres.Close();
 response.Close();

 m_swSAPCostCentres = new StreamWriter(Properties.Settings.Default.SAPInt + @"\SAPCostCentres" + ".txt");

In some reason it throws exception at

 m_swSAPCostCentres.Write(srSAPCostObjects.ReadToEnd());

Am not sure why,some one please guide me.

It may be a typo but you're initializing the m_swSAPCostCentres after you're referencing it. Could that be the problem ?

I guess the issue is that the file you are trying to write already exists and is opened by another application.

try to delete the file:

Properties.Settings.Default.SAPInt + @"\SAPCostCentres" + ".txt"

if it exists, before trying to create it again.

in your code you should also add a try catch and make sure you either use using statement to wrap disposable objects or call the close method in the catch or finally block so that streams and other objects are always closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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