Renaming image while saving using Handler

Last Reply 5 days ago By pandeyism

Posted 5 days ago

Hi friends,

i am saving image to folder in that time i ll rename image as save as.. but it showing error... my code below

while save as function called that time showing below error

The SaveAs method is configured to require a rooted path, and the path '1323' is not rooted

<%@ WebHandler Language="C#" Class="uploadImage" %>

using System;
using System.Web;

public class uploadImage : IHttpHandler {
    public string _html = string.Empty; 
    public void ProcessRequest (HttpContext context) {
        try
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
               var newfilename = context.Request.Form.ToString().Split('=')[1]; // new filename is 1111
              
                    HttpPostedFile file = files[0];
                    string oldfilename = file.FileName; //oldfilename is 1323
                    string fname = context.Server.MapPath("~/empimages/" + oldfilename);
                    file.SaveAs(newfilename); // showing error as The SaveAs method is configured to require a rooted path, and the path '1323' is not rooted.
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("ok");
        }
        catch (Exception ex)
        {
            _html = "ERROR~";
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

 

You are viewing reply posted by: pandeyism 5 days ago.
Posted 5 days ago

Hi sureshMGR,

You have not assigned folder name where you want to save your file. Refer below code change your code.

Code

Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
    public string _html = string.Empty;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            if (context.Request.Files.Count > 0)
            {
                HttpFileCollection files = context.Request.Files;
                var newfilename = context.Request.Form.ToString().Split('=')[1]; // new filename is 1111
                HttpPostedFile file = files[0];
                string oldfilename = file.FileName; //oldfilename is 1323
                string fname = context.Server.MapPath("~/empimages/" + oldfilename);
                file.SaveAs("~/empimages/" + newfilename); // showing error as The SaveAs method is configured to require a rooted path, and the path '1323' is not rooted.
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("ok");
        }
        catch (Exception ex)
        {
            _html = "ERROR~";
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}