I wrote a simple C# program to transfer ACCDE files from a FTP server to a client's desktop. The transferring seems to work fine, however, when I open the file and try to use the program, it gives me the message "Requested type library or wizard is not a VBA project."
When I transfer the ACCDB source code, it seems to work fine. This is the transfer function:
private void DownloadFileFTP(string fileName, string localFilePath, bool isXmlSchema)
{
string ftpFilePath = redacted;
if (isXmlSchema)
{
ftpFilePath = ftpFilePath + fileName;
label3.Text = "Fetching update information...";
}
else
{
ftpFilePath = ftpFilePath + Properties.Settings.Default.Customer + "/" + fileName;
label3.Text = "Updating " + fileName;
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Credentials = new NetworkCredential(redacted, redacted);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = Properties.Settings.Default.SSL;
request.UsePassive = Properties.Settings.Default.Passive;
int bytesRead = 0;
byte[] buffer = new byte[2048];
Stream reader = request.GetResponse().GetResponseStream();
FileStream fs = new FileStream(localFilePath, FileMode.Create);
while(true)
{
bytesRead = reader.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
fs.Write(buffer, 0, bytesRead);
}
fs.Close();
}
My questions, I suppose, are: am I doing something wrong here? Do ACCDE files not play nice with FileStreams or something? I am still quite new to .NET so any help would be very appreciated.
EDIT: It seems one of the references was causing the problem.
You didn't close stream and ftpWebRequest.
Try this, made with you script, just copy/paste (fix some error if it have :) ):
private void DownloadFileFTP(string fileName, string localFilePath, bool isXmlSchema)
{
FileStream fs = null;
try
{
fileName = Regex.Replace(fileName.ToString(), #"\s.*$", "").Trim();
string ftpFilePath = redacted;
if (isXmlSchema)
{
ftpFilePath = ftpFilePath + fileName;
label3.Text = "Fetching update information...";
}
else
{
ftpFilePath = ftpFilePath + Properties.Settings.Default.Customer + "/" + fileName;
label3.Text = "Updating " + fileName;
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpFilePath);
request.Credentials = new NetworkCredential(redacted, redacted);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.EnableSsl = Properties.Settings.Default.SSL;
request.UsePassive = Properties.Settings.Default.Passive;
int bytesRead = 0;
int bufferSize = 2048;
byte[] buffer = new byte[bufferSize];
Stream reader = request.GetResponseStream();
bytesRead = reader.Read(buffer, 0, bufferSize);
fs = new FileStream(localFilePath, FileMode.Create);
while (bytesRead > 0)
{
fs.Write(buffer, 0, bytesRead);
bytesRead = reader.Read(buffer, 0, bufferSize);
}
reader.Close();
request.Close();
}
catch (Exception ex)
{
label3.Text = "Error: " + ex.ToString;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
Related
I have write code for transfer file from FTP server to local server and after transfer 2 or 3 files it throwing exception error The remote server returned an error: 150 Opening data channel for file download
All File transfered successfully in FileZila but error coming in asp.net application.
I do the following code
protected string TransferFile(string strPath, string strFtpPath, string strFtpUser, string strFtpPwd, string strSubClientFTPPath, string strSubClientFTPUser, string strSubClientFTPPwd, string strFileName, string strConvFileName, string strFileSize)
{
string strSuccess = "";
FtpWebRequest reqFTP;
try
{
Double Size = 0;
string strLocalFileSize = "";
if (File.Exists(strPath + strConvFileName))
{
Size = ((Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length)) > 0 && Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length)) < 1024) ? 1 : (Math.Round(Convert.ToDouble(new FileInfo(strPath + strConvFileName).Length) / 1024 + 0.0001)));
strLocalFileSize = Size + "KB";
}
if (!File.Exists(strPath + strConvFileName) || strFileSize != strLocalFileSize)
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFtpPath + strFileName.Replace("#", "%23")));
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
reqFTP.EnableSsl = true;
reqFTP.Timeout = Timeout.Infinite;
reqFTP.KeepAlive = true;
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
//reqFTP.UseBinary = true;
//reqFTP.UsePassive = false;
reqFTP.Credentials = new NetworkCredential(strFtpUser, strFtpPwd);
// lblTransferredFile.Text = "Transferring " + strFileName + " ......";
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
// lblTransferredFile.Text = "Transferring " + strFileName + " ......";
readCount = ftpStream.Read(buffer, 0, bufferSize);
//if (readCount > 0)
//{
FileStream outputStream = new FileStream(strPath +
strConvFileName, FileMode.Create);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
strSuccess = "";
}
else
{
strSuccess = "File Exists";
}
}
catch (Exception ex)
{
strSuccess = ex.Message;
ClientScript.RegisterStartupScript(this.GetType(), "strScript", "<script>alert('" + ex.Message.Trim().Replace("'", "") + "');</script>");
}
return strSuccess;
}
I've encountered this today after installing kb 4519976. Uninstalling this KB solved the problem. Could you check if this is also the solution in your case.
Context was an ftps tls 1.2 ECHDE connection which fails at the stage where the extra connection is started.
I am using ftp for downloading a zip file(size 10 MB to 70 MB) from server it was perfectly downloading but, when the network is slow, the error the operation has timed out in ftp is showing and then it comes to catch(Exception ex) in that the download() is called once again so it is redownloading again and again.
This project is created in .NET framework 4.0
I have increased the time of ftpWebRequest.Timeout = 6000; but still it doesn't work
public void Download(string localDirectory,string localFilename,string remoteDirectory,string remoteFileName)
{
string client_path=Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(localDirectory)));
string appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string configFile = System.IO.Path.Combine(appPath, "PACS.exe.config");
ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = configFile;
System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
config.AppSettings.Settings["client_path"].Value = client_path;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
string str = Path.Combine(localDirectory, localFilename);
FileInfo fileInfo = new FileInfo(str);
FileStream fileStream = (FileStream)null;
WebException webException;
try
{
string path = Path.GetDirectoryName(Path.GetDirectoryName(remoteDirectory));
string path1 = Path.GetDirectoryName(Path.GetDirectoryName(localDirectory));
WebRequest sizeRequest = WebRequest.Create("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip");
sizeRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");
sizeRequest.Method = WebRequestMethods.Ftp.GetFileSize;
int size = (int)sizeRequest.GetResponse().ContentLength;
FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri("ftp://" + "IP" + ":" + "port" + "/" + "C:\\KINSOLUTIONS\\Team\\Images\\1" + ".zip")) as FtpWebRequest;
ftpWebRequest.Credentials = (ICredentials)new NetworkCredential("UserName", "Password");
ftpWebRequest.UsePassive = true;
ftpWebRequest.Timeout = 6000;
ftpWebRequest.KeepAlive = false;
ftpWebRequest.Method = "RETR";
ftpWebRequest.UseBinary = true;
fileStream = new FileStream(path1 + ".zip", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
using(Stream responseStream = (ftpWebRequest.GetResponse() as FtpWebResponse).GetResponseStream())
{
byte[] buffer = new byte[32768];
int count = responseStream.Read(buffer, 0, 32768);
long num = (long)count;
int post = 0;
while (size != post || count != 0 )
{
bool result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
while (!result)
{
result = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (result)
{
fileStream.Close();
Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
}
}
fileStream.Write(buffer, 0, count);
count = responseStream.Read(buffer, 0, 32768);
int position = (int)fileStream.Position;
num += (long)count;
post = position;
}
fileStream.Close();
}
}
catch (WebException ex)
{
if (fileStream != null)
fileStream.Close();
this.Download(localDirectory, localFilename, remoteDirectory, remoteFileName);
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
Is there any other option for downloading the zip file in slow network?
I have made a download program in C#. It is a queue downloader.
You can see how it works here: Click Express Downloader
Is there any faster method to download?
Here is the method i use, it must support resume support.
private void Download(object startPoint)
{
try
{
try
{
//int startPointInt = Convert.ToInt32(startPoint);
Int64 startPointInt = Convert.ToInt64(startPoint);
webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.AddRange(startPointInt);
webRequest.Credentials = CredentialCache.DefaultCredentials;
webResponse = (HttpWebResponse)webRequest.GetResponse();
Int64 fileSize = webResponse.ContentLength;
strResponse = webResponse.GetResponseStream();
if (startPointInt == 0)
{
strLocal = new FileStream(txtPath.Text + "\\" + filename, FileMode.Create, FileAccess.Write, FileShare.None);
}
else
{
strLocal = new FileStream(txtPath.Text + "\\" + filename, FileMode.Append, FileAccess.Write, FileShare.None);
}
int bytesSize = 0;
byte[] downBuffer = new byte[4096];
while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, bytesSize);
this.Invoke(new UpdateProgessCallback(this.UpdateProgress), new object[] { strLocal.Length, fileSize + startPointInt });
if (goPause == true)
{
break;
}
}
}
catch { }
}
finally
{
strResponse.Close();
strLocal.Close();
}
}
You have to do two things,
Get faster bandwidth
Change block size from 4096 to something like 8192 or any number which can be hold in memory easily.
I am re-developing an app for a scanner used for stocktakes to allow it to work while offline. In order to do so, I need to be able to download a file from a laptop which is acting as a server. I got to a point at which it works, but only downloads that are of size 9.53mb max. How can I tweak the code to allow for larger files. I would need to allow for a maximum size of around 30mb.
Here is my code:
try
{
string full_url = App.prouductUrl + App.stStocktakeId + ".db";
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(full_url);
httpRequest.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
System.IO.Stream dataStream = httpResponse.GetResponseStream();
// Dim str As Stream = cdsMobileLibrary2.http_download.getfile(filename)
//50 meg
byte[] inBuf = new byte[10000001];
int bytesToRead = Convert.ToInt32(inBuf.Length);
int bytesRead = 0;
while (bytesToRead > 0)
{
int n = dataStream.Read(inBuf, bytesRead, bytesToRead);
if (n == 0)
{
break; // TODO: might not be correct. Was : Exit While
}
bytesRead += n;
bytesToRead -= n;
}
FileStream fstr = new FileStream(#"\productdb\" + App.stStocktakeId + ".db", FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(inBuf, 0, bytesRead);
dataStream.Close();
fstr.Close();
string size = loginRes.getFromJSON("size");
FileInfo fi = new FileInfo(#"\productdb\" + App.stStocktakeId + ".db");
MessageBox.Show("File Size is:" + fi.Length + "Compared to:" + size);
}
catch { }
In my code I want to upload and download a specific JSON-File to a FTP-Server.
The serializing works great and also the upload. When i look up the file via - for example - FileZilla, the content of the file is correct. (on the server)
But when i download this file with my application (and with my code - NOT with FileZilla), I don't get any exceptions, but the file is nearly empty. This is the only content:
{}
And here is my code for downloading:
string ResponseDescription = "";
FtpWebRequest req = (FtpWebRequest)FtpWebRequest.Create("ftp://" + "ftp.strato.com" + "/" + verzeichnis + "/" + file.Name);
req.Method = WebRequestMethods.Ftp.DownloadFile;
req.Credentials = new NetworkCredential(this.benutzer, this.passwort);
req.UseBinary = true;
req.UsePassive = false;
req.Proxy = null;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[2048];
FileStream fs = new FileStream(destinationFolder + #"/" + destinationFile.Name, FileMode.Create);
int ReadCount = stream.Read(buffer, 0, buffer.Length);
while (ReadCount > 0)
{
fs.Write(buffer, 0, ReadCount);
ReadCount = stream.Read(buffer, 0, buffer.Length);
}
ResponseDescription = response.StatusDescription;
fs.Close();
stream.Close();
return true;
}
catch (Exception e)
{
MessageBox.Show(e.Message); // TODO - better Errorhandling
return false;
}
I found the solution. It was my mistake. The problem wasnt the download - the code was correct (as you said).
After downloading the file the JSON-Deserialization runs and here was the cause. I had a little mistake in my deserialization-logic.