Solved

C# ftp login and sendin file

Posted on 2012-03-12
7
267 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 50

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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Is Your DevOps Pipeline Leaking?

Is your CI/CD pipeline a hodge-podge of randomly connected tools? You’ve likely got a tool to fix one problem & then a different tool to fix another, resulting in a cluster of tools with overlapping functionality. Learn how to optimize your pipeline with Gartner's recommendations

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
TCP Chat/GPS application security thru firewall 4 55
c#, datatable, aspx 4 51
C# Change the instruction to user. 11 39
Make borderless form movable by user 2 27
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

734 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