January 12, 2011

FTP Automated file upload

Code To generate files
1.)ftpcmds.txt ('ll contain the information of username password and File to be uploaded)
2.)FTPScript.cmd('ll Contain the command to upload the file on the specified server)



public void GenerateFiles()
{
// create a writer and open the file
System.IO.StreamWriter file =
new System.IO.StreamWriter(Application .StartupPath+"/ftpcmds.txt");

// write a line of text to the file
file.WriteLine("UserName");
file.WriteLine("Password");
file.WriteLine("type binary");
file.WriteLine("cd Test");
file.WriteLine("put C:\\Test\\Test.doc");
file.WriteLine("bye");


// close the stream
file.Close();


// create a writer and open the file
System.IO.StreamWriter filecmd =
new System.IO.StreamWriter(Application.StartupPath + "/FTPScript.cmd");

// write a line of text to the file
filecmd.WriteLine(@"FTP -s: PathFor ftpcmds.txt file FTPServerIP");


// close the stream
filecmd.Close();

}

The above will generate these two files.
Now below code will run the command from FTPScript.cmd


private void Upload_File(object sender, EventArgs e)
{
try

{
GenerateFiles();
string path = Application.StartupPath + "/FTPScript.cmd";


var procStartInfo = new ProcessStartInfo(path, "")
{

CreateNoWindow = false,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true
};

var proc = new Process { StartInfo = procStartInfo };
proc.Start();
//proc.StandardInput.WriteLine(password);
//proc.WaitForExit(3500);
proc.StandardInput.Flush();

// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
string error = proc.StandardError.ReadToEnd();

}

catch (System.ComponentModel.Win32Exception)
{
// logger.Error("Error is occuring at the process start while decrypting the file");
// MessageBox.Show("");
}

catch (System.IO.IOException)
{
// logger.Error("The write operation could not be performed");
// MessageBox.Show("The write operation could not be performed.");

}

No comments:

Post a Comment