Canvas
Canvas

Reputation: 5897

c# illegal character in file path

Hey guys I have this piece of code that will first store a path in a variable, check if that path exists, if not create it. then take that path and add my file name to it.

Here is the code

appData = string.Format("{0}{1}\"", controller.Server.MapPath("~/App_Data/"), Guid.NewGuid().ToString());

if (!Directory.Exists(appData))
    Directory.CreateDirectory(appData);

filePath = string.Format("{0}\"{1}", appData, model.File.FileName);
model.File.SaveAs(filePath);
data.Add("attachment", filePath);

But when it gets to the SaveAs function it states

Illegal character in path

AppDath = C:\Users\Ben\Documents\Team Foundation Server\Team Projects\Shared\Orchard 1.6\Orchard\src\Orchard.Web\App_Data\392216b5-32ad-41f4-82bf-e074b13f25df\"

Any idea why?

Upvotes: 2

Views: 1048

Answers (2)

Raphaël Althaus
Raphaël Althaus

Reputation: 60493

use Path.Combine

filePath = Path.Combine(appData, model.File.FileName);

same to create appData path

appData = Path.Combine(controller.Server.MapPath("~/App_Data"), Guid.NewGuid().ToString());

Upvotes: 5

Kamil T
Kamil T

Reputation: 2216

Use

filePath = string.Format(@"{0}\"{1}", appData, model.File.FileName);

The @ char show the compiler that the string doesn't have any backslashed characters. Normaly, you use the \ prefix in some special chars, like \n means a newline. You string has a \, so the compiler tries to resolve it with the next char in the string.

Another way is to escape the backslash with the second one, like this:

filePath = string.Format(@"{0}\\"{1}", appData, model.File.FileName);

Upvotes: 1

Related Questions