Solved

C# ftp login and sendin file

Posted on 2012-03-12
7
258 Views
Last Modified: 2012-03-15
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
Comment
Question by:pauledwardian
  • 3
  • 3
7 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 37710826
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
 
LVL 49

Expert Comment

by:Gustav Brock
ID: 37712175
Bedtime here ... but perhaps you can get some ideas from this:

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

/gustav
0
 

Author Comment

by:pauledwardian
ID: 37712197
do you guys know a source that can help in writing FTPS function instead of FTP?
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 37712327
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
 

Author Comment

by:pauledwardian
ID: 37712598
Yup. I have to change it to FTPS since the website does no longer supports FTP.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 37712971
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
 

Author Closing Comment

by:pauledwardian
ID: 37727896
Thanks!
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now