Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 277
  • Last Modified:

C# ftp login and sendin file

Can someone help to figure out the error.
I change the code to

            if (Create_File())
            {
                Send_File();
            }

Open in new window

But, it doesnt even go through the Send_File and only Creates the file. and if I do it like:
 Create_File(); 
Send_File();

Open in new window


Then it says that the file is being used by another process BUT it was closed in:
 sr.Close();

Please advice: (Fyi: I just started learning C# so please be clear in your comments! Thanks, Paul)
namespace class
{
  
    public partial class Form1 : Form
    {
        static string path = "C:\\file";
        static string ftpServerIP = "172.16.11.133";
        static string ftpUserID = "admin";
        static string ftpPassword = "admin123";


        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Create_File())
            {
                Send_File();
            }
            Send_File();
            GC.Collect();
            
            //checkConnection();
        }

        private static bool Create_File()
        {
            
            string connstr = "Data Source=PCNumber;Initial Catalog=AdventureWorks;User ID=sa;Password=admin123";
            SqlConnection conn = new SqlConnection
            {
                ConnectionString = connstr 
            };
            try
            {
                try
                {
                    conn.Open();
                }
                catch (Exception e)
                {
                    Write_Error(e);
                    return false;
                }

                SqlDataAdapter da = new SqlDataAdapter("Exec ('Select * From HumanResources.Employee')", conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "HumanResources.Employee");
                if (ds.Tables["HumanResources.Employee"].Rows.Count > 0)
                {
                    //StreamWriter sr = File.AppendText(AppDomain.CurrentDomain.BaseDirectory + @"\UpLoad" + sfile);
                    StreamWriter sr = File.AppendText(path + sfile);
                    foreach (DataRow myRow in ds.Tables["HumanResources.Employee"].Rows)
                    {
                        if (myRow[4].ToString() == string.Empty)
                        {
                            MessageBox.Show("Row 3  " + myRow[4].ToString());
                            sr.WriteLine(string.Concat(new object[] { 
                            "'", myRow[0], "','", myRow[1], "','", myRow[2], "',", string.Empty, ",'", myRow[4], "','", myRow[5], "',", string.Empty, ",'", myRow[7], 
                            "',", myRow[8], ",'", myRow[9], "'"
                         }));
                        }
                        else
                        {
                            MessageBox.Show("Row 3  " + myRow[3].ToString());
                            DateTime dt = DateTime.Parse(myRow[3].ToString());
                            DateTime MyDate = DateTime.Parse(myRow[6].ToString());
                            sr.WriteLine(string.Concat(new object[] { 
                            "'", myRow[0], "','", myRow[1], "','", myRow[2], "',", dt.ToString("yyyy-MM-dd HH:mm:ss"), ",'", myRow[4], "','", myRow[5], "',", MyDate.ToString("yyyy-MM-dd HH:mm:ss"), ",'", myRow[7], 
                            "',", myRow[8], ",'", myRow[9], "'"
                         }));
                        }
                    }
                    sr.Flush();
                    sr.Close();
                    GC.Collect();
                    return true;
                }
                //return File.Exists(path + @"\UpLoad" + sfile);
                return File.Exists(path + sfile);

            }
            catch (Exception e)
            {
                conn.Close();
                Write_Error(e);
                return false;
            }

        }

        [STAThread]
        /*private static void Main(string[] args)
        {
            if (Create_File())
            {
                Send_File();
            }
            GC.Collect();
        }*/
        
        private static void Send_File()
        {
       
            try
            {
                path = changepath();
                Upload(path.ToString());
                MessageBox.Show("File Name " + path.ToString());
            }
            catch (Exception e)
            {
                Write_Error(e);
                MessageBox.Show("Error file" + e);
            }
            finally
            {
                GC.Collect();
            }
        }
        public static string changepath()
        {
            path = path +sfile;
            return path;
        }


        private static void Write_Error(Exception ex)
        {
            //ExceptionManager.Publish(ex);
        }

        // Properties
        private static string sfile
        {
            get
            {
                string sjend;
                string sjdate = DateTime.Now.DayOfYear.ToString();
                switch (sjdate.Length)
                {
                    case 1:
                        sjend = "00" + sjdate;
                        break;

                    case 2:
                        sjend = "0" + sjdate;
                        break;

                    default:
                        sjend = sjdate;
                        break;
                }
                return (@"\s0001009001." + sjend);
            }
        }
        private static void Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);

            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;

            // Create FtpWebRequest object from the Uri provided
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));

            // Provide the WebPermission Credintials
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

            // By default KeepAlive is true, where the control connection is not closed
            // after a command is executed.
            reqFTP.KeepAlive = false;

            // Specify the command to be executed.
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // Specify the data transfer type.
            reqFTP.UseBinary = true;

            // Notify the server about the size of the uploaded file
            reqFTP.ContentLength = fileInf.Length;

            // The buffer size is set to 2kb
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;

            // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
            FileStream fs = fileInf.OpenRead();

            try
            {
                // Stream to which the file to be upload is written
                Stream strm = reqFTP.GetRequestStream();

                // Read from the file stream 2kb at a time
                contentLen = fs.Read(buff, 0, buffLength);

                // Till Stream content ends
                while (contentLen != 0)
                {
                    // Write Content from the file stream to the FTP Upload Stream
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // Close the file stream and the Request Stream
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Upload Error");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
        }
      
    }

}

Open in new window

0
pauledwardian
Asked:
pauledwardian
  • 3
  • 3
1 Solution
 
käµfm³d 👽Commented:
Have you tried stepping through the Create_File method to see what the flow of execution is? Perhaps by putting a breakpoint on each return statement in that method you can deduce which condition is causing a false to be returned.

On a side note, there usually isn't a need to call GC.Collect in normal coding, and especially not as many times as you are doing in the above. I think you can remove those calls without incident. Invoking garbage collection manually incurs a good bit of overhead.
0
 
Gustav BrockCIOCommented:
Bedtime here ... but perhaps you can get some ideas from this:

http://www.codeproject.com/Articles/343913/Simple-FTP-library-in-Csharp

/gustav
0
 
pauledwardianAuthor Commented:
do you guys know a source that can help in writing FTPS function instead of FTP?
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
käµfm³d 👽Commented:
Not off the top of my head. I helped a co-worker craft one in Java, but it was at a lower level (i.e. directly sending FTP commands and opening up raw sockets). I'd have to see what the equivalent to an SSLSocket in C# would be.

Are you certain its FTPS and not SFTP?
0
 
pauledwardianAuthor Commented:
Yup. I have to change it to FTPS since the website does no longer supports FTP.
0
 
käµfm³d 👽Commented:
I can't say that I've used it, but you might look into this project: http://ftps.codeplex.com/

It will probably be better put together than anything I could throw together in a short timeframe  : )

If this is intended to be a learning experience as well, I can provide a highlight of what goes on for FTPS, and I could try to convert my Java example [it ain't too pretty  ; )  ]. If it's more of a "get 'er done" situation, then I think the above project will fit your needs.
0
 
pauledwardianAuthor Commented:
Thanks!
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now