#c# #razor
Вопрос:
Сейчас я разрабатываю текстовый редактор razor base, все, что я хочу сделать, это один раз прочитать данные CSV, использовать эти данные в следующем посте. Это будет означать создание глобальных переменных после открытия страницы, используйте эти переменные в полном объеме исходного кода программирования. Я пытался это сделать, однако мне нужна перезагрузка csv-файлов после публикации, Как я могу использовать один раз для чтения csv-данных (списка) по всему миру, как это.
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections;
namespace ARTFAQ.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public string error;
public List<Documents> doc1 = new List<Documents>();
public string indx;
public string evnt;
public string evnt2;
public string bodyelement;
public string htmldata;
public string textdata;
[BindProperty]
[Required]
public string Name { get; set; }
//public List<Documents> doc1 { get; set; }
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public async Task OnGetAsync()
{
//blobから設定ファイルをダウンロードする。
//storageAccountの作成(接続情報の定義)
//アカウントネームやキー情報はAzureポータルから確認できる。
var accountName = "";
var accessKey = "";
var credential = new
Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accessKey);
var storageAccount = new CloudStorageAccount(credential, true);
//blob
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("");
// Retrieve reference to a blob named "filename"
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference("FILES-1000000.xml");
string files2;
using (var memoryStream2 = new MemoryStream())
{
await blockBlob2.DownloadToStreamAsync(memoryStream2);
files2 = System.Text.Encoding.UTF8.GetString(memoryStream2.ToArray());
}
// convert string to stream
byte[] byteArray2 = Encoding.UTF8.GetBytes(files2);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream2 = new MemoryStream(byteArray2);
// convert stream to string
StreamReader reader2 = new StreamReader(stream2);
XmlSerializer serializer = new XmlSerializer(typeof(filelists));
filelists result = null;
result = (filelists)serializer.Deserialize(reader2);
reader2.Close();
string data = "";
for (int i = 0; i <= result.list.Length - 1; i )
{
//result.list[i].file
CloudBlockBlob blockBlob3 = container.GetBlockBlobReference(result.list[0].file);
using (var memoryStream3 = new MemoryStream())
{
if (i == 0)
{
await blockBlob3.DownloadToStreamAsync(memoryStream3);
data = System.Text.Encoding.UTF8.GetString(memoryStream3.ToArray());
var doc = data.Split("<seprt>");
var counter = 0;
string id = "";
string tytle = "";
string body = "";
string htmlbody = "";
foreach (string value in doc)
{
if (counter % 4 == 0)
{
id = doc[counter];
}
if (counter % 4 == 1)
{
tytle = doc[counter];
}
if (counter % 4 == 2)
{
body = doc[counter];
}
if (counter % 4 == 3)
{
htmlbody = doc[counter];
//error = id tytle body htmlbody;
doc1.Add(new Documents()
{
id = id,
tytle = tytle,
body = body,
htmlbody = htmlbody,
});
}
counter = 1;
}
}
}
}
error = "open";
}
// OnPost return type is JsonResult
public async Task<JsonResult> OnPost()
{
indx = Request.Form["indx"];
evnt = Request.Form["evnt"];
textdata = Request.Form["textbody"];
htmldata = Request.Form["htmlbody"];
//blobから設定ファイルをダウンロードする。
//storageAccountの作成(接続情報の定義)
//アカウントネームやキー情報はAzureポータルから確認できる。
var accountName = "";
var accessKey = "";
var credential = new
Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accessKey);
var storageAccount = new CloudStorageAccount(credential, true);
//blob
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("");
// Retrieve reference to a blob named "filename"
CloudBlockBlob blockBlob = container.GetBlockBlobReference("");
string files;
using (var memoryStream = new MemoryStream())
{
await blockBlob.DownloadToStreamAsync(memoryStream);
files = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(files);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
MemoryStream stream = new MemoryStream(byteArray);
// convert stream to string
StreamReader reader = new StreamReader(stream);
XmlSerializer serializer = new XmlSerializer(typeof(filelists));
filelists result = null;
result = (filelists)serializer.Deserialize(reader);
reader.Close();
string data = "";
bodyelement = "";
CloudBlockBlob blockBlob2 = container.GetBlockBlobReference(result.list[0].file);
using (var memoryStream = new MemoryStream())
{
await blockBlob2.DownloadToStreamAsync(memoryStream);
data = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
var doc = data.Split("<seprt>");
if (evnt == "listclick")
{
bodyelement = doc[3 (Int32.Parse(indx)) * 4];
}
else if (evnt == "save")
{
doc[2 (Int32.Parse(indx)) * 4] = textdata;
doc[3 (Int32.Parse(indx)) * 4] = htmldata;
//bodyelement = textdata htmldata;
saveDoc(doc);
bodyelement = "saved";
}
}
await Task.Delay(100);
if (!ModelState.IsValid)
{
return new JsonResult("JSONResponse: Error occurred. Please retry.");
}
return new JsonResult(bodyelement);
}
public async void saveDoc(String[] doc)
{
var CSV = "";
var counter = 0;
foreach (string value in doc)
{
if (counter != doc.Length)
{
CSV = CSV doc[counter] "<seprt>";
}
else
{
CSV = CSV doc[counter];
}
counter = 1;
}
//blobから設定ファイルをダウンロードする。
//storageAccountの作成(接続情報の定義)
//アカウントネームやキー情報はAzureポータルから確認できる。
var accountName = "";
var accessKey = "";
var credential = new
Microsoft.WindowsAzure.Storage.Auth.StorageCredentials(accountName, accessKey);
var storageAccount = new CloudStorageAccount(credential, true);
//blob
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.GetContainerReference("documentsdata");
// Retrieve reference to a blob named "filename"
CloudBlockBlob blockBlob = container.GetBlockBlobReference("C#-1000000.csv");
var options = new BlobRequestOptions()
{
ServerTimeout = TimeSpan.FromMinutes(10)
};
using (var stream = new MemoryStream(Encoding.Default.GetBytes(CSV), false))
{
await blockBlob.UploadFromStreamAsync(stream);
}
}
//
/// <remarks/>
///
public class Itempost
{
public string name { get; set; }
public string id { get; set; }
}
public class SendEmailRequest
{
public int PortraitId { get; set; }
public string To { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public List<int> FileIds { get; set; }
}
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class filelists
{
private filelistsEntry[] listField;
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("entry", IsNullable = false)]
public filelistsEntry[] list
{
get
{
return this.listField;
}
set
{
this.listField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class filelistsEntry
{
private string fileField;
private byte keyField;
/// <remarks/>
public string file
{
get
{
return this.fileField;
}
set
{
this.fileField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}
}
}
}
Ответ №1:
измените общедоступный список doc1 = новый список(); на общедоступный статический список doc1 = новый список(); решена проблема.