>Hi,
>
>I got some code off this page:
>
>
http://www.aspnettutorials.com/tutorials/network/net-fileupload-aspnet2-csharp.aspx>
>to allow a user to upload a file from a web page using the FileUpload control in ASP.NET.
>
>Here's the code:
>
>
if (this.uplLogo.HasFile)
> {
> string filepath = this.uplLogo.PostedFile.FileName;
> string pat = @"\\(?:.+)\\(.+)\.(.+)";
> Regex r = new Regex(pat);
> //run
> Match m = r.Match(filepath);
> string file_ext = m.Groups[2].Captures[0].ToString();
> string filename = m.Groups[1].Captures[0].ToString();
> string file = filename + "." + file_ext;
>
> //save the file to the server
> this.uplLogo.PostedFile.SaveAs(Server.MapPath(".\\") + file);
>
> //lblStatus.Text = "File Saved to: " + Server.MapPath(".\\") + file; if (Session["LogoFile"] != null)
> oAppSettings.LogoFile = file;
> }
>
>I am getting an error at this line:
>
>
string file_ext = m.Groups[2].Captures[0].ToString();
>
>and the error is:
>
>System.ArgumentOutOfRangeException was unhandled by user code
> Message="Specified argument was out of the range of valid values.\r\nParameter name: i"
> Source="System"
> ParamName="i"
> StackTrace:
> at System.Text.RegularExpressions.CaptureCollection.GetCapture(Int32 i)
> at System.Text.RegularExpressions.CaptureCollection.get_Item(Int32 i)
> at SamaanSystems.IAS.Web.SettingsManager.btnSave_Click(Object sender, EventArgs e) in C:\Development\Mere Mortals .NET Framework 2008\SamaanSystems\IAS.Web\Admin\SettingsManager.aspx.cs:line 51
> at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
> at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
> at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
> at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
> at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
> at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
> InnerException:
>
>I am guessing that m.Groups[2] does not exist, but this is my first time using regular expressions. The file I am trying to upload is this:
>
>"C:\Documents\Arrive Alive\images\AALogo.jpg"
>
>Any idea what I need to do to fix this?
Frank,
You need to test for m.Success
string filepath = @"\folder\aaa.bb";
string pat = @"\\(?:.+)\\(.+)\.(.+)";
var m = Regex.Match(filepath, pat);
if (m.Success)
{
Console.WriteLine("{0}", m.Groups[1].Captures[0].ToString());
Console.WriteLine("{0}", m.Groups[2].Captures[0].ToString());
}
else
Console.WriteLine("No match");
Console.ReadLine();
Gregory