HttpRequest.MapPath (Método) (String)
Actualización: noviembre 2007
Asigna la ruta de acceso virtual especificada a una ruta de acceso física.
Ensamblado: System.Web (en System.Web.dll)
public String MapPath( String virtualPath )
public function MapPath( virtualPath : String ) : String
Parámetros
- virtualPath
- Tipo: System.String
Ruta de acceso virtual (absoluta o relativa) de la solicitud actual.
| Excepción | Condición |
|---|---|
| HttpException | No hay ningún objeto HttpContext definido para la solicitud. |
Precaución: |
|---|
La propiedad MapPath puede contener información confidencial sobre el entorno de host. El valor devuelto no debe mostrarse a los usuarios. |
El ejemplo de código siguiente utiliza el método MapPath para convertir una ruta de acceso virtual en una ruta de acceso física completa en el servidor. Este ejemplo tiene dos partes:
Una página .aspx asigna la ruta de acceso, lee el archivo y muestra los resultados de la operación de lectura.
Una clase, UpperCaseFilterStream, que cambia todos los caracteres que se le pasan a mayúsculas.
La primera parte del ejemplo muestra cómo convertir una ruta de acceso virtual en una ruta de acceso física completa utilizando el método MapPath. Esta ruta de acceso física se pasa a continuación a un objeto StreamReader que obtiene el contenido del archivo. A continuación, se llama al método Write para mostrar el contenido del archivo en la página. La propiedad Filter se utiliza para adjuntar un filtro a la secuencia de respuesta que convierte en mayúsculas todo el texto que se muestra en la página.
<%@ Page Language="C#" %> <%@ Import Namespace="System.IO" %> <%@ import Namespace="Samples.AspNet.CS.Controls" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> private void Page_Load(object sender, EventArgs e) { // Filter the text to be rendered as all uppercase. Response.Filter = new UpperCaseFilterStream(Response.Filter); // Convert a virtual path to a fully qualified physical path. string fullpath = Request.MapPath("~\\TestFile.txt"); try { // Read the contents of the file using a StreamReader. using (StreamReader sr = new StreamReader(fullpath)) while (sr.Peek() >= 0) { Response.Write((char)sr.Read()); } Message.Text = "Reading the file was successful."; } catch (Exception ex) { Message.Text = "The process failed."; } } </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>HttpResponse.MapPath Example</title> </head> <body> <form id="form1" runat="server"> <asp:Label id="Message" runat="server"/> </form> </body> </html>
<%@ Page Language="VJ#" %>
<%@ import Namespace="Samples.AspNet" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
private void Page_Load(Object sender, EventArgs e)
{
// Filter the text to be rendered as all uppercase.
get_Response().set_Filter(new UpperCaseFilterStream(get_Response().
get_Filter()));
} //Page_Load
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ASP.NET Example</title>
</head>
<body>
<% get_Response().Write("This text will be rendered all uppercase." ); %>
</body>
</html>
La segunda parte del ejemplo muestra una clase que hereda de Stream y convierte todos los caracteres de una secuencia en mayúsculas. Coloque este código en la carpeta App_Code de su aplicación.
using System; using System.IO; using System.Text; namespace Samples.AspNet.CS.Controls { public class UpperCaseFilterStream : Stream // This filter changes all characters passed through it to uppercase. { private Stream strSink; private long lngPosition; public UpperCaseFilterStream(Stream sink) { strSink = sink; } // The following members of Stream must be overriden. public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return lngPosition; } set { lngPosition = value; } } public override long Seek(long offset, System.IO.SeekOrigin direction) { return strSink.Seek(offset, direction); } public override void SetLength(long length) { strSink.SetLength(length); } public override void Close() { strSink.Close(); } public override void Flush() { strSink.Flush(); } public override int Read(byte[] buffer, int offset, int count) { return strSink.Read(buffer, offset, count); } // The Write method actually does the filtering. public override void Write(byte[] buffer, int offset, int count) { byte[] data = new byte[count]; Buffer.BlockCopy(buffer, offset, data, 0, count); string inputstring = Encoding.ASCII.GetString(data).ToUpper(); data = Encoding.ASCII.GetBytes(inputstring); strSink.Write(data, 0, count); } } }
package Samples.AspNet;
import System.*;
import System.IO.*;
public class UpperCaseFilterStream extends Stream
{
// This filter changes all characters passed through it to uppercase.
private Stream strSink;
private long lngPosition;
public UpperCaseFilterStream(Stream sink)
{
strSink = sink;
} //UpperCaseFilterStream
// The following members of Stream must be overriden.
/** @property
*/
public boolean get_CanRead()
{
return true;
} //get_CanRead
/** @property
*/
public boolean get_CanSeek()
{
return true;
} //get_CanSeek
/** @property
*/
public boolean get_CanWrite()
{
return true;
} //get_CanWrite
/** @property
*/
public long get_Length()
{
return 0;
} //get_Length
/** @property
*/
public long get_Position()
{
return lngPosition;
} //get_Position
/** @property
*/
public void set_Position(long value)
{
lngPosition = value;
} //set_Position
public long Seek(long offset, System.IO.SeekOrigin direction)
{
return strSink.Seek(offset, direction);
} //Seek
public void SetLength(long length)
{
strSink.SetLength(length);
} //SetLength
public void Close()
{
strSink.Close();
} //Close
public void Flush()
{
strSink.Flush();
} //Flush
public int Read(ubyte buffer[], int offset, int count)
{
return strSink.Read(buffer, offset, count);
} //Read
// The Write method actually does the filtering.
public void Write(ubyte buffer[], int offset, int count)
{
ubyte data[] = new ubyte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
for (int i = 0; i < count; i++) {
// Change lowercase chars to uppercase.
if (data[i] >= 'a' && data[i] <= 'z') {
data[i] -= (Convert.ToInt16('a') - Convert.ToInt16('A'));
data[i] -= (Convert.ToInt16('a') - Convert.ToInt16('A'));
}
}
strSink.Write(data, 0, count);
} //Write
} //UpperCaseFilterStream
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.
Precaución: