Uploading File on Server using OpenFile Dialog in Silverlight

Hi there,

In Silverlight it Requires 2 steps to upload file on server.

1. In ViewModel read the file

           private void Event_ReadXLSFile ()
          {
            byte[] FileBytes;
            OpenFileDialog XLSFile = new OpenFileDialog();
            XLSFile.Filter = "Excel Files(*.xls)|*.xls";

             if (XLSFile.ShowDialog() == true)
             {
               //  read all the data into byte[]
                Stream FileStream = XLSFile.File.OpenRead();
                FileBytes = new byte[Convert.ToInt32(FileStream.Length)];
                FileStream.Read(FileBytes, 0, Convert.ToInt32(FileStream.Length));


                gSrvZ01S290Client.convertByteToCollectionAsync(FileBytes, Session.SessionID);
               }
              }

Last Line calling the service and handing him over the byte[] of our file. Service method will provide this byte[] array to our Business Logic Class i.e. Server where we convert it back like below.

2. On the Server

        /// <summary>
        /// create excel file at location specified in resource file
        /// </summary>
        /// <param name="array"></param>
        private bool ConvertByteToXLSFile (byte[] array)
        {
            bool Success = false;
            string path = null;
            string strSaveFileName = "Import.xls";
            string strSaveFileDir = rsCommon.SharedPath + "LocationMaster\\Import";
            string strSaveFile = Path.Combine(strSaveFileDir, strSaveFileName);

            // check save file directory
            if (!Directory.Exists(strSaveFileDir))
            {
                Directory.CreateDirectory(strSaveFileDir);
            }

            try
            {
                path = strSaveFile;

                //  if file exists delete it
                if (File.Exists(path))
                {
                    File.Delete(path);
                }

                //  write array into excel file
                File.WriteAllBytes(path, array);
                Success = true;
            }

            catch (Exception)
            {
                Success = false;
            }

            return Success;

        }

In above method rsCommon.SharedPath  is a resource file attribute in which i stored the path to save the file.

Hope it will help you !

Comments

Popular Posts