我被要求创建一个程序,用户可以从他的本地或任何网络驱动器浏览一些txt文件,每行用分隔符解析它并将其存储在DB中。问题是我的代码无法获取确切的URL,而是返回安装了应用程序解决方案的URL,返回错误,说明找不到文件。我一直在环顾四周,我知道asp .net无法获得确切的文件路径,最好有文件上传。有没有办法在我阅读它之前不必将它保存在解决方案文件夹/服务器中?
我的代码是:
protected void btnUploadSave_Click(object sender, EventArgs e)
{
string path =
string.Format(
CultureInfo.InvariantCulture,
Strings.NewObjectPath,
_root,
fuUpload.FileName);
//string x = fuUpload.PostedFile.FileName;
OpenFile(path);
}
它返回路径但不返回项目的实际位置。 恩。实际位置是c:\ my docs \ download \ someFile.txt,它返回c:\ my docs \ vs 2010 \ Project \ myAppSoltn \ someFile.txt
如果由于安全问题而无法获取确切的文件loc,有没有办法可以通过知道文件名来打开文件?下面的lcode不起作用但我会骗取这样的东西吗?
private void OpenFile(String path)
{
path = @"~\someFile.txt";
// Delete the file if it exists.
AirDataAccess access = new AirDataAccess();
using (TextFieldParser parser = new TextFieldParser(path))
{
parser.Delimiters = new string[] { "," };
while (true)
{
string[] words = parser.ReadFields();
if (words == null)
break;
else
{
AirData airData = null;
if (words != null)
{
airData = new AirData();
airData.DateAired = Convert.ToDateTime(words[0]);
if (adBusiness.isValidUniqueCode(airData.UniqueCode))
access.InsertAirData(airData);
}
}
}
}
}
这是myp页面:
<asp:View ID="vUpload" runat="server">
<asp:Panel ID="pnlUpload" runat="server" DefaultButton="btnUploadSave">
<table border="0" cellpadding="5" cellspacing="0">
<thead>
<tr>
<td class="header">Upload a File</td>
</tr>
</thead>
<tbody>
<tr>
<td>
<asp:RequiredFieldValidator ID="rfvUpload" runat="server" ErrorMessage="A file name is required" ControlToValidate="fuUpload" SetFocusOnError="true">* </asp:RequiredFieldValidator>
<asp:FileUpload ID="fuUpload" runat="server" CssClass="button" Width="400px" />
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td align="right">
<asp:Button ID="btnUploadCancel" runat="server" CausesValidation="false" CssClass="button" Text="Cancel" UseSubmitBehavior="false" onclick="Cancel" />
<asp:Button ID="btnUploadSave" runat="server" CssClass="button" Text="Upload" onclick="btnUploadSave_Click" />
</td>
</tr>
</tfoot>
</table>
</asp:Panel>
</asp:View>
答案 0 :(得分:0)
TextFieldParser
可以Stream
作为输入吗?或StreamReader
?
如果它可以使用流,您可以在OpenFile
方法中使用此行:
using (TextFieldParser parser = new TextFieldParser(fuUpload.PostedFile.InputStream))
这样您就不必在处理之前将文件保存到服务器。
但如果TextFieldParser
仅对文件有效,您可以将上传的文件保存在临时文件中,然后将其删除:
string tempFileName = System.IO.Path.GetTempFileName();
fuUpload.PostedFile.SaveAs(tempFileName);
// process your file
System.IO.File.Delete(tempFileName);