Solved

C# ftp login and sendin file

Posted on 2012-03-12
7
272 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 75

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 51

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
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 
LVL 75

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 75

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

[Webinar] Learn How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video, viewers will be given step by step instructions on adjusting mouse, pointer and cursor visibility in Microsoft Windows 10. The video seeks to educate those who are struggling with the new Windows 10 Graphical User Interface. Change Cu…
In this video, viewers are given an introduction to using the Windows 10 Snipping Tool, how to quickly locate it when it's needed and also how make it always available with a single click of a mouse button, by pinning it to the Desktop Task Bar. Int…

634 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