I am working on a project and I need to upload a CSV file and read it.
I am working in Visual Studio 2010 and MVC3 and C# language.
If I am to use html fileuplaod control, how I am suppose to take the uploaded file and read it in the client side itself without saving the file in the server.
Do I have to use the jquery?
I have searched but did not get solution to meet my requirements. I am new to MVC3 and CSV file handling and quite confused.
*What is the easiest way to upload a .csv file and read it in order to save it in the database.
A clear solution would be highly appreciated.Thanks.
What you can do is save the file on server, then after you read the content from them you can delete the file.
I think there is a no way you can read the from client side. You must upload it on ur server to read that.
using (StreamReader CsvReader = new StreamReader(input_file))
{
string inputLine = "";
while ((inputLine = CsvReader.ReadLine()) != null)
{
values.Add(inputLine.Trim().Replace(",", "").Replace(" ", ""));
}
CsvReader.Close();
return values;
}
You should be able to access the data without saving it - using the InputStream property
http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream.aspx
and this (see Paulius Zaliaduonis answer)
private async Task<string> ProcessAsync(string surveyId)
{ if(!Request.Content.IsMimeMultipartContent())
{
return "|UnsupportedMediaType";
}
try
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.LoadIntoBufferAsync().ConfigureAwait(false);
await Request.Content.ReadAsMultipartAsync(provider).ConfigureAwait(false);
HttpContent content = provider.Contents.FirstOrDefault();
if(content != null)
{
Stream stream = await content.ReadAsStreamAsync().ConfigureAwait(false);
using (StreamReader CsvReader = new StreamReader(stream))
{
string inputLine = "";
while ((inputLine = CsvReader.ReadLine()) != null)
{
string[] vars = inputLine.Split(',');
}
CsvReader.Close();
//return values;
}
}
}
catch(Exception e)
{
return e.ToString();
}
return "Nothing To Process";
}
Related
A client uses our web application to parse a XML file for a database. Then uses the information from the XML file from the database for various other things. I am as of now stream reading and stream writing the file. When the files were smaller, they used to be parsed into a string then inserted into a the database record. The problem is the file is so large that computers don't have enough RAM to process a string that large, how can I process this file and still store it in a database?
using (var reader = new StreamReader(outputPath))
{
string line = string.Empty;
bool save = false;
using (var sWriter = new StreamWriter(inputPath))
{
while ((line = reader.ReadLine()) != null)
{
System.Diagnostics.Debug.WriteLine(line);
if (line.Contains("<SaveDataFromScout>"))
{
sWriter.WriteLine("<SaveDataFromScout>");
save = true;
continue;
}
else if (line.Contains("</SaveDataFromScout>"))
{
sWriter.WriteLine(line);
save = false;
}
if (save)
{
if (line.Contains("ELEMENT TEXT"))
line = line.Replace("ELEMENT TEXT", "ELEMENTTEXT");
sWriter.WriteLine(line);
}
}
}
}
//string workbookXML = System.IO.File.ReadAllText(outputPath);
transactionID = DAC.ExecuteScalar
(
db.ConnectionString,
"dbo.cwi_InsertTransaction",
new SqlParameter("#TransactionTypeID", transactionTypeID),
new SqlParameter("#UploadedFileName", fileDataLink),
//new SqlParameter("#UploadedFileXml", workbookXML),
new SqlParameter("#CurrentUserID", CurrentUser.UserID)
);
Do you see the commented out code where it previously was converted into a string to be parsed into the database? Well, this works, but it does not work for files that are around 888MB large.
Load the file directly into SQL Server, XML column type using bulk load:
INSERT INTO T(XmlCol)
SELECT * FROM OPENROWSET(
BULK 'c:\SampleFolder\SampleData3.txt',
SINGLE_BLOB) AS x;
More documentation:
https://learn.microsoft.com/en-us/sql/relational-databases/import-export/examples-of-bulk-import-and-export-of-xml-documents-sql-server?view=sql-server-2017
public static async Task Store(ObservableCollection<Product> list)
{
Uri path = new Uri("ms-appx:///ListCollection.json");
var store = await StorageFile.GetFileFromApplicationUriAsync(path);
var stream = File.OpenWrite(store.Path);
var serialize = new DataContractJsonSerializer(typeof(ObservableCollection<Product>));
serialize.WriteObject(stream, list);
}
Ok this is the piece of code that I used to serialize a collection , works very well , no problem with it , but what I want and tried and no success. I created a JSON file in my project. I want to store and stream data to that file. I tried some methods but no success , how do I open a stream to a file that is currently in my project?
EDITED : Commented the code that was working and wrote what I intend to do. Thanks for support.
When I get to this line
var stream = File.OpenWrite(store.Path); it says that is inaccesible.
What I intend to do is serialize some data to a file called ListCollection.json that is emtpy , that file is project file. It might be the stream or it might be the file that gives me that error. No idea.
My guess is that your project file is located in the installation directory of your application and as far as I know you can't just write to that directory.
You would have to put a deployment action in your solution that writes the desired project file to the application data directory. There you should be able to write it.
I looked through some of the documentation and came accross this:
MSDN
The app's install directory is a read-only location.
I found a Link which makes use of a little hack or so it seems.
I am not sure if this will work if the application is deployed etc.
but you can try this to write the file.
I am not sure if you need a stream or not but feel free to comment:
private void Button_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<string> list = new ObservableCollection<string>();
list.Add("Hallo");
list.Add("Welt");
Task t = Store(list);
}
public static async Task Store(ObservableCollection<string> list)
{
StorageFile file = await GetStorageFileFromApplicationUriAsync();
if (file == null)
{
file = await GetStorageFileFromFileAsync();
}
if (file != null)
{
await file.DeleteAsync();
await CreateFileInInstallationLocation(list);
}
}
private static async Task<StorageFile> GetStorageFileFromFileAsync()
{
StorageFile file = null;
if (file == null)
{
try
{
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
file = await folder.GetFileAsync("ListCollection.json");
}
catch
{ }
}
return file;
}
private static async Task<StorageFile> GetStorageFileFromApplicationUriAsync()
{
StorageFile file = null;
try
{
Uri path = new Uri("ms-appx:///ListCollection.json");
file = await StorageFile.GetFileFromApplicationUriAsync(path);
}
catch
{ }
return file;
}
private static async Task CreateFileInInstallationLocation(ObservableCollection<string> list)
{
var pkg = Windows.ApplicationModel.Package.Current;
var installedLocationFolder = pkg.InstalledLocation;
try
{
var file = await installedLocationFolder.CreateFileAsync("ListCollection.json", Windows.Storage.CreationCollisionOption.GenerateUniqueName);
var filePath = file.Path;
DataContractJsonSerializer serialize = new DataContractJsonSerializer(typeof(ObservableCollection<String>));
using (Stream stream = await file.OpenStreamForWriteAsync())
{
serialize.WriteObject(stream, list);
stream.Flush();
}
}
catch (Exception ex)
{
var msg = ex.Message;
}
}
What this basically does is:
Find the file
Delete the file
Create a new file
Write your JSON to the file
I am really not an expert on this matter and it even to me seems pretty hacky but it apparently does the job.
If you can avoid writing to the install directory do it and use the method Frank J proposed
I am using a web service that returns me some data. I am writing that data in a text file. my problem is that I am having a file already specified in the c# code, where I want to open a dialog box which ask user to save file in his desired location. Here I am posting code which I have used. Please help me in modifying my code. Actually after searching from internet, all are having different views and there is lot of changes in code required where as I do not want to change my code in extent. I am able to write the content in test file but how can I ask user to enter his desire location on computer?
StreamWriter file = new StreamWriter("D:\\test.txt");
HttpWebRequest webreq = (HttpWebRequest)WebRequest.Create(yahooURL);
// Get the response from the Internet resource.
HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse();
// Read the body of the response from the server.
StreamReader strm =
new StreamReader(webresp.GetResponseStream(), Encoding.ASCII);
string content = "";
for (int i = 0; i < symbols.Length; i++)
{
// Loop through each line from the stream,
// building the return XML Document string
if (symbols[i].Trim() == "")
continue;
content = strm.ReadLine().Replace("\"", "");
string[] contents = content.ToString().Split(',');
foreach (string dataToWrite in contents)
{
file.WriteLine(dataToWrite);
}
}
file.Close();
Try this
using (WebClient Client = new WebClient ())
{
Client.DownloadFile("http://www.abc.com/file/song/a.mpeg", "a.mpeg");
}
I'm using IsolatedStorage in a Silverlight application for caching, so I need to know if the file exists or not which I do with the following method.
I couldn't find a FileExists method for IsolatedStorage so I'm just catching the exception, but it seems to be a quite general exception, I'm concerned it will catch more than if the file doesn't exist.
Is there a better way to find out if a file exists in IsolatedStorage than this:
public static string LoadTextFromIsolatedStorageFile(string fileName)
{
string text = String.Empty;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
try
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName,
FileMode.Open, isf))
{
using (StreamReader sr = new StreamReader(isfs))
{
string lineOfData = String.Empty;
while ((lineOfData = sr.ReadLine()) != null)
text += lineOfData;
}
}
return text;
}
catch (IsolatedStorageException ex)
{
return "";
}
}
}
From the "manual" (.net framework 2.0 Application Development Foundation):
Unlike the application programming interface (API) for files stored arbitrarily
in the file system, the API for files in Isolated Storage does not support checking
for the existence of a file directly like File.Exists does. Instead, you need to ask the
store for a list of files that match a particular file mask. If it is found, you can open the
file, as shown in this example
string[] files = userStore.GetFileNames("UserSettings.set");
if (files.Length == 0)
{
Console.WriteLine("File not found");
}
else
{
// ...
}
I need to read the contents of the Web.Config and send them off in an email, is there a better way to do the following:
string webConfigContents = String.Empty;
using (FileStream steam = new FileStream(
Server.MapPath("~/web.config"),
FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = new StreamReader(steam))
{
webConfigContents = reader.ReadToEnd();
}
}
I dont want to lock the file. Any ideas?
Edit - I need a raw dump of the file, I cant attach the file (Webhost says nay!), and im not looking for anything specific inside it
You can replace your code with this:
string webConfigContents = File.ReadAllText(Server.MapPath("~/web.config"));
The file will be locked for writing while it is being read, but not for reading. But I don't think this will be a problem, because the web.config file is not usually being written to (since this would restart the web application).
By using the asp.net api.
System.Configuration.Configuration rootWebConfig1 =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (0 < rootWebConfig1.AppSettings.Settings.Count)
{
System.Configuration.KeyValueConfigurationElement customSetting =
rootWebConfig1.AppSettings.Settings["customsetting1"];
if (null != customSetting) {
Console.WriteLine("customsetting1 application string = \"{0}\"", customSetting.Value);
}
else {
Console.WriteLine("No customsetting1 application string");
}
}