473,385 Members | 1,907 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

FTP trasnferred as binary even with FTP_TRANSFER_TYPE_ASCII specified

YT
Hi,

In my C# code I call WININET's FtpPutFile function to FTP upload text
files. It has a flags parameters to specify whether the transfer
should be done in binary or ASCII. I've specified
FTP_TRANSFER_TYPE_ASCII which is mapped to constant 1, however the
file is still transferred as binary. Could anyone suggest what went
wrong? Thanks!
public class FTPUpload
{
public const int FTP_TRANSFER_TYPE_ASCII = 1;
public const int FTP_TRANSFER_TYPE_BINARY = 2;

private static readonly log4net.Ext.EventID.IEventIDLog evlog =
log4net.Ext.EventID.EventIDLogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().De claringType);

[DllImport("WININET", EntryPoint="InternetOpen", SetLastError=true,
CharSet= CharSet.Auto)]
static extern IntPtr InternetOpen (
string agent,
int accessType,
string proxyName,
string proxyBypass,
int flags
);

[DllImport("WININET",
EntryPoint="InternetCloseHandle",SetLastError=true ,
CharSet=CharSet.Auto)]
static extern bool InternetCloseHandle(IntPtr hInternet);

[DllImport("WININET",
EntryPoint="InternetConnect",SetLastError=true, CharSet=CharSet.Auto)]
static extern IntPtr InternetConnect (
IntPtr internetHandle,
string serverName,
int serverPort,
string username,
string password,
int service,
int flags,
int context
);
[DllImport("WININET", EntryPoint="FtpSetCurrentDirectory",
SetLastError=true, CharSet=CharSet.Auto)]
static extern bool FtpSetCurrentDirectory (
IntPtr connect,
string directory
);

[DllImport("WININET",
EntryPoint="FtpGetCurrentDirectory",SetLastError=t rue,
CharSet=CharSet.Auto)]
static extern bool FtpGetCurrentDirectory(
IntPtr connect,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,
ref int bufferLength
);

[DllImport("WININET",
EntryPoint="InternetAttemptConnect",SetLastError=t rue,
CharSet=CharSet.Auto)]
static extern int InternetAttemptConnect(int dwReserved);

[DllImport("WININET", EntryPoint="FtpPutFile",SetLastError=true,
CharSet=CharSet.Auto)]
static extern bool FtpPutFile(
IntPtr connect,
string localFile,
string newRemoteFile,
int flags,
int context
);

[DllImport("WININET", EntryPoint="InternetGetLastResponseInfo",
SetLastError=true, CharSet=CharSet.Auto)]
static extern bool InternetGetLastResponseInfo(
out int error,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,
ref int bufferLength
);

static readonly int ERROR_SUCCESS = 0;
static readonly int INTERNET_OPEN_TYPE_DIRECT = 1;
static readonly int INTERNET_SERVICE_FTP = 1;

public static string GetLastFTPError()
{
int errorCode = -1;
int bufferLength = 512;

StringBuilder errorMessage = new StringBuilder(bufferLength);

if(! InternetGetLastResponseInfo(out errorCode,errorMessage,ref
bufferLength))
return "Could not determine error message. ";
else
return errorMessage.ToString();
}

public static void Put(
string ftpServer,
int ftpPort,
string userName,
string password,
string sourceFilePath,
string destinationFileName,
string destinationDirectory,
int flags
)
{
IntPtr inetHandle = IntPtr.Zero;
IntPtr ftpconnectHandle = IntPtr.Zero;

try
{
//check for inet connection
if (InternetAttemptConnect(0) != ERROR_SUCCESS)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToInternet,
string.Format("Failed in INet Connection attempt: {0}",
GetLastFTPError()));
}

//connect to inet
inetHandle = InternetOpen("EM Insight
Publishing",INTERNET_OPEN_TYPE_DIRECT,null,null,0) ;

if (inetHandle == IntPtr.Zero)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToInternet,
string.Format("Unable to make INet Connection with error: {0}",
GetLastFTPError()));
}

//connect to ftp
ftpconnectHandle =
InternetConnect(inetHandle,ftpServer,ftpPort,userN ame,password,INTERNET_SERVICE_FTP,
0,0);

if (ftpconnectHandle == IntPtr.Zero)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToFTPServer,
string.Format("Failed on connect to ftp server with error: {0}",
GetLastFTPError()));
}
//set to desired directory on FTP server
if("" != destinationDirectory)
{
if (! FtpSetCurrentDirectory(ftpconnectHandle,
destinationDirectory))
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedSettingD estinationDirectory,
string.Format("Couldn't set desired directory on FTP server
with error: {0}", GetLastFTPError()));
}
}

int buffSize = 512;
System.Text.StringBuilder dir = new StringBuilder(buffSize);

//upload file to server
if (! FtpPutFile(ftpconnectHandle, sourceFilePath,
destinationFileName, flags, 0) )
{
throw new ErrorCodeException(EMErrorCode.ecFTPPutFailure,
string.Format("Couldn't upload file to FTP server with error:
{0}", GetLastFTPError()));
}

}
catch(ErrorCodeException ex)
{
evlog.Error("FTP upload failed. ", ex);
throw;
}
catch (Exception ex)
{
ErrorCodeException ecex = new
ErrorCodeException(EMErrorCode.ecFTPFailure, ex);
evlog.Error("Generic FTP upload failure. ", ecex);
throw ecex;
}
finally
{
//close connection to ftp.microsoft.com
if (ftpconnectHandle != IntPtr.Zero)
InternetCloseHandle(ftpconnectHandle);

ftpconnectHandle = IntPtr.Zero;

//close connection to inet
if (inetHandle != IntPtr.Zero)
InternetCloseHandle(inetHandle);

inetHandle = IntPtr.Zero;
}
}

Sep 18 '07 #1
1 4298
YT,

You aren't showing the code where you are calling Put and setting the
flags. Are you sure that you are passing it in?

Also, are you using .NET 2.0? If so, have you considered using the
FtpWebRequest class in the System.Net namespace?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"YT" <ku*******@gmail.comwrote in message
news:11*********************@w3g2000hsg.googlegrou ps.com...
Hi,

In my C# code I call WININET's FtpPutFile function to FTP upload text
files. It has a flags parameters to specify whether the transfer
should be done in binary or ASCII. I've specified
FTP_TRANSFER_TYPE_ASCII which is mapped to constant 1, however the
file is still transferred as binary. Could anyone suggest what went
wrong? Thanks!
public class FTPUpload
{
public const int FTP_TRANSFER_TYPE_ASCII = 1;
public const int FTP_TRANSFER_TYPE_BINARY = 2;

private static readonly log4net.Ext.EventID.IEventIDLog evlog =
log4net.Ext.EventID.EventIDLogManager.GetLogger(
System.Reflection.MethodBase.GetCurrentMethod().De claringType);

[DllImport("WININET", EntryPoint="InternetOpen", SetLastError=true,
CharSet= CharSet.Auto)]
static extern IntPtr InternetOpen (
string agent,
int accessType,
string proxyName,
string proxyBypass,
int flags
);

[DllImport("WININET",
EntryPoint="InternetCloseHandle",SetLastError=true ,
CharSet=CharSet.Auto)]
static extern bool InternetCloseHandle(IntPtr hInternet);

[DllImport("WININET",
EntryPoint="InternetConnect",SetLastError=true, CharSet=CharSet.Auto)]
static extern IntPtr InternetConnect (
IntPtr internetHandle,
string serverName,
int serverPort,
string username,
string password,
int service,
int flags,
int context
);
[DllImport("WININET", EntryPoint="FtpSetCurrentDirectory",
SetLastError=true, CharSet=CharSet.Auto)]
static extern bool FtpSetCurrentDirectory (
IntPtr connect,
string directory
);

[DllImport("WININET",
EntryPoint="FtpGetCurrentDirectory",SetLastError=t rue,
CharSet=CharSet.Auto)]
static extern bool FtpGetCurrentDirectory(
IntPtr connect,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,
ref int bufferLength
);

[DllImport("WININET",
EntryPoint="InternetAttemptConnect",SetLastError=t rue,
CharSet=CharSet.Auto)]
static extern int InternetAttemptConnect(int dwReserved);

[DllImport("WININET", EntryPoint="FtpPutFile",SetLastError=true,
CharSet=CharSet.Auto)]
static extern bool FtpPutFile(
IntPtr connect,
string localFile,
string newRemoteFile,
int flags,
int context
);

[DllImport("WININET", EntryPoint="InternetGetLastResponseInfo",
SetLastError=true, CharSet=CharSet.Auto)]
static extern bool InternetGetLastResponseInfo(
out int error,
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,
ref int bufferLength
);

static readonly int ERROR_SUCCESS = 0;
static readonly int INTERNET_OPEN_TYPE_DIRECT = 1;
static readonly int INTERNET_SERVICE_FTP = 1;

public static string GetLastFTPError()
{
int errorCode = -1;
int bufferLength = 512;

StringBuilder errorMessage = new StringBuilder(bufferLength);

if(! InternetGetLastResponseInfo(out errorCode,errorMessage,ref
bufferLength))
return "Could not determine error message. ";
else
return errorMessage.ToString();
}

public static void Put(
string ftpServer,
int ftpPort,
string userName,
string password,
string sourceFilePath,
string destinationFileName,
string destinationDirectory,
int flags
)
{
IntPtr inetHandle = IntPtr.Zero;
IntPtr ftpconnectHandle = IntPtr.Zero;

try
{
//check for inet connection
if (InternetAttemptConnect(0) != ERROR_SUCCESS)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToInternet,
string.Format("Failed in INet Connection attempt: {0}",
GetLastFTPError()));
}

//connect to inet
inetHandle = InternetOpen("EM Insight
Publishing",INTERNET_OPEN_TYPE_DIRECT,null,null,0) ;

if (inetHandle == IntPtr.Zero)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToInternet,
string.Format("Unable to make INet Connection with error: {0}",
GetLastFTPError()));
}

//connect to ftp
ftpconnectHandle =
InternetConnect(inetHandle,ftpServer,ftpPort,userN ame,password,INTERNET_SERVICE_FTP,
0,0);

if (ftpconnectHandle == IntPtr.Zero)
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedConnecti ngToFTPServer,
string.Format("Failed on connect to ftp server with error: {0}",
GetLastFTPError()));
}
//set to desired directory on FTP server
if("" != destinationDirectory)
{
if (! FtpSetCurrentDirectory(ftpconnectHandle,
destinationDirectory))
{
throw new
ErrorCodeException(EMErrorCode.ecFTPFailedSettingD estinationDirectory,
string.Format("Couldn't set desired directory on FTP server
with error: {0}", GetLastFTPError()));
}
}

int buffSize = 512;
System.Text.StringBuilder dir = new StringBuilder(buffSize);

//upload file to server
if (! FtpPutFile(ftpconnectHandle, sourceFilePath,
destinationFileName, flags, 0) )
{
throw new ErrorCodeException(EMErrorCode.ecFTPPutFailure,
string.Format("Couldn't upload file to FTP server with error:
{0}", GetLastFTPError()));
}

}
catch(ErrorCodeException ex)
{
evlog.Error("FTP upload failed. ", ex);
throw;
}
catch (Exception ex)
{
ErrorCodeException ecex = new
ErrorCodeException(EMErrorCode.ecFTPFailure, ex);
evlog.Error("Generic FTP upload failure. ", ecex);
throw ecex;
}
finally
{
//close connection to ftp.microsoft.com
if (ftpconnectHandle != IntPtr.Zero)
InternetCloseHandle(ftpconnectHandle);

ftpconnectHandle = IntPtr.Zero;

//close connection to inet
if (inetHandle != IntPtr.Zero)
InternetCloseHandle(inetHandle);

inetHandle = IntPtr.Zero;
}
}
Sep 19 '07 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: yaipa | last post by:
What would be the common sense way of finding a binary pattern in a ..bin file, say some 200 bytes, and replacing it with an updated pattern of the same length at the same offset? Also, the...
103
by: Steven T. Hatton | last post by:
§27.4.2.1.4 Type ios_base::openmode Says this about the std::ios::binary openmode flag: *binary*: perform input and output in binary mode (as opposed to text mode) And that is basically _all_ it...
8
by: John Forkosh | last post by:
I have a C program that writes binary output to stdout, which works fine in Unix/Linux. But when someone else compiled and ran it in Windows, every time the program emitted a 0x0A, Windows...
5
by: pembed2003 | last post by:
Hi, I have a question about how to walk a binary tree. Suppose that I have this binary tree: 8 / \ 5 16 / \ / \ 3 7 9 22 / \ / \ / \
11
by: Steve | last post by:
Hi, i know this is an old question (sorry) but its a different problem, i need to write a binary file as follows 00000011 00000000 00000000 00000101 00000000 11111111
0
by: Tamir Khason | last post by:
I'm distribute my component to client and he's complians about " Binary format of the specified custom attribute was invalid." error while using with studio (while add to component toolbar or just...
7
by: John Dann | last post by:
I'm trying to read some binary data from a file created by another program. I know the binary file format but can't change or control the format. The binary data is organised such that it should...
7
by: smith4894 | last post by:
Hello all, I'm working on writing my own streambuf classes (to use in my custom ostream/isteam classes that will handle reading/writing data to a mmap'd file). When reading from the mmap...
3
by: masood.iqbal | last post by:
Hi, Kindly excuse my novice question. In all the literature on ifstream that I have seen, nowhere have I read what happens if you try to read a binary file using the ">>" operator. I ran into...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.