WPF - file related operations

One file download

    First, add a reference to RestSharp. Here I have referenced RestSharp, so the "Install" button is not clickable.



    Some attachments (that is, files) must be downloaded according to the MediaID file identification and authentication conditions. The following is the program content:

/// <summary>
        /// Get the picture and save it locally and return the local address
        /// </summary>
        /// <param name="mediaId">File ID</param>
        /// <returns></returns>
        public static DownloadFileModel DownloadFile(string mediaId)
        {
            var client = new RestClient("http://....here is the domain name of the download address");

            DownloadFileModel result = new DownloadFileModel();//Customized model, including data stream of MemoryStream type and file name of string type

            try
            {
                client.Timeout = 20000;//Timeout limit
                client.Authenticator = new HttpBasicAuthenticator("Account", "Password");//Add authentication, which is defined according to the interface requirements
                var request = new RestRequest("API接口"), Method.GET);
                IRestResponse response = client.Execute(request);

                if (response.ErrorException != null)
                {
                    throw new Exception(response.ErrorMessage);
                }

                if (response.StatusCode == HttpStatusCode.OK && response.ResponseStatus == ResponseStatus.Completed)
                {
                    var item = response.Headers.Where(h => h.Name == "Content-Disposition").FirstOrDefault();
                    if (item != null)
                    {
                        ContentDisposition contentDisposition = new ContentDisposition(item.Value.ToString());
                        result.Filename = HttpUtility.UrlDecode(contentDisposition.FileName);
                    }
                }

                result.DownloadStream = new MemoryStream(response.RawBytes);//Get the data stream

                return result;
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return null;
        }

    Or download directly according to the full address URL of the file, the procedure is as follows:

/// <summary>
        /// Download pictures according to URl
        /// </summary>
        /// <param name="downloadUrl">File download URL</param>
        /// <returns></returns>
        public static  DownloadFileModel DownloadPic(string downloadUrl)
        {  
            DownloadFileModel result = new DownloadFileModel();//Custom data model, including data stream of type MemoryStream and file name of string type

            try
            {
                WebClient web = new WebClient();
                byte[] fileBytes = web.DownloadData(downloadUrl);

                var filename = Convert.ToString(DateTime.Now.Ticks);//The file name is named after the current timestamp
                result.DownloadStream = new MemoryStream(fileBytes);//Get the data stream
                result.Filename = filename;
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return null;
            }

        }

Second save file

    When saving a picture, a file selection box is given so that the user can choose which path to save the file to.

/// <summary>
        /// Select the path and save the file
        /// </summary>
        /// <param name="fileName">File name with suffix</param>
        /// <param name="stream">File stream</param>
        /// <returns></returns>
        public static string SaveStream(string fileName, MemoryStream stream)
        {
            if (stream == null) return null;
                     Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
                    //set file type
                    //Writing rules for example: txt files(*.txt)|*.txt
                    //saveFileDialog.Filter = "txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*|图片|*.jpg;*.png;*.gif;*.bmp;*.jpeg";
                    // Possible path name to get
                    string localFilePath = "";
                    //Set the default file name (can not be set)
                    saveFileDialog.FileName = fileName;
                    //Whether the save dialog remembers the last opened directory
                    saveFileDialog.RestoreDirectory = true;
                    // Show save file dialog box
                    bool? result = saveFileDialog.ShowDialog();
                    //Click the save button to enter
                    if (result == true)
                    {
                        //get file path
                        localFilePath = saveFileDialog.FileName;

                        using (var fs = new FileStream(localFilePath, FileMode.Create, FileAccess.ReadWrite))
                        {
                            fs.Write(stream.ToArray(), 0, ((int)stream.Length));
                        }
                return localFilePath;
                    }
            return null;
        }


Three open files

     Generally specify the default path of the openFileDialog object and the selected file. After the openFileDialog.ShowDialog() method is called, a file selection box with the specified path will pop up. When the user clicks the "Open" button, the result here will be true, and then according to the openFileDialog .FileName gets the selected file path (path + file name + suffix), and finally calls the Process.Start() method to open the target file. Notice. If there is no application that opens this file in the current system, an exception will be thrown after calling the Process.Start() method, and the exception information can be viewed in the catch.

  /// <summary>
        /// Open the file directory
        /// </summary>
        /// <param name="fileName">File name with suffix</param>
        /// <returns></returns>
        public static OpenFileModel OpenFilePath(string filePath)
        {
            var openFileModel = new OpenFileModel(); //Customized data model, with bool type open success status and string type error message
            if (filePath == null || filePath.Length == 0) {
                openFileModel.status = false;
                return openFileModel;
            }
            bool exits = File.Exists(filePath);
            if (!exits)
            {
                openFileModel.status = false;
                return openFileModel;
            }
            int index = filePath.LastIndexOf('.');
            if (index < 0) {
                    openFileModel.status = false;
                    return openFileModel;              
            }

            var fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);//Get the file name
            var path = filePath.Substring(0, filePath.LastIndexOf("\\"));//Get the file path
            try {
               
                Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
                openFileDialog.FileName = fileName;
                openFileDialog.InitialDirectory = path;
                // Show save file dialog box
                bool? result = openFileDialog.ShowDialog();//Open the directory where the target file is located
                if (result == true)//
                {
                    Console.WriteLine(openFileDialog.FileName);
                    System.Diagnostics.Process.Start(openFileDialog.FileName);//Open the file selected by the user
                }
                openFileModel.status = true;
                return openFileModel;
            }
            catch (Exception e) {
                openFileModel.status = true;
                openFileModel.message = e.Message;
                return openFileModel;
            }

            
        }


Four select files

    Here, the function of filtering pictures is realized with the help of OpenFileDialog .

    Program description: Filter is the filter condition, and all files are filtered by default; InitialDirectory is the path opened by default.

private async void btnChooseFile(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.AddExtension = true;
            dialog.Filter = "All images|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff";
            dialog.InitialDirectory = "c:\\";
            dialog.RestoreDirectory = true;
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                var filePath = dialog.FileName;
                if (!string.IsNullOrWhiteSpace(filePath))
                {
                    var ext = Path.GetExtension(filePath);
                    bool isImage = ".jpg|.jpeg|.bmp|.gif|.png|.tiff".Contains(ext.ToLower());
                    //Following other specific operations based on the obtained file path
                }
            }

           
        }


Five upload files

    Program description: OperationStatus is my custom request status model, including request result status (success/failure) and text information.

public async Task<OperationStatus> DoUpload(string path) {
            var operationStatus = new OperationStatus();
            if (path == null || !File.Exists(path))
            {
                operationStatus.Status = false;
                operationStatus.Message = "File does not exist";
                return operationStatus;
            }
            try
            {
                var fileName = Path.GetFileName(path);
                var model = new MediaFileModel
                {
                    ThumbUrl = path,
                    MediaLength = new FileInfo(path).Length,
                    RealName = fileName
                };
                var stream = File.OpenRead(path);
                var bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                //The following is the specific upload operation based on the obtained file path and byte stream
                stream.Close();
            }
            catch (Exception e)
            {
                operationStatus.Message = e.Message;
                operationStatus.Status = false;
            }

            return operationStatus;
        }




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325683945&siteId=291194637