I try to move files with code below from ftp://a.domain.con to ftp://b.domain.con
Public Function TransferFile(ByVal originalFile As String, ByVal destinationFile As String, ByVal userName As String, ByVal password As String) As String
Try
Dim fStream As New FileStream(destinationFile, FileMode.Create)
Dim fileRequest As FileWebRequest = DirectCast(FtpWebRequest.Create(New Uri(originalFile)), FileWebRequest)
fileRequest.Method = WebRequestMethods.Ftp.DownloadFile
fileRequest.Credentials = New NetworkCredential(userName, password)
Dim response As WebResponse = fileRequest.GetResponse()
Dim stream As Stream = response.GetResponseStream()
Dim buffer As Byte() = New Byte(1023) {}
Dim size As Long = 0
Dim totalRead As Integer = stream.Read(buffer, 0, buffer.Length)
While totalRead > 0
size += totalRead
fStream.Write(buffer, 0, totalRead)
totalRead = stream.Read(buffer, 0, 1024)
End While
fStream.Close()
stream.Close()
Return "File transfered"
Catch ex As SecurityException
Return ex.Message
Catch ex As Exception
Return ex.Message
End Try
End Function
The problem is that on the first line
Dim fStream As New FileStream(destinationFile, FileMode.Create)
i get The given path's format is not supported. error.
The Original filename is ftp://a.domain.con/102425547_��������_14.2.2011_1.zip
and the Destination one is ftp://b.domain.con/102425547_��������_14.2.2011_1.zip
By the way here comes the StackTrace...
at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, AccessControlActions control, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
and the �������� characters are Greek ones!
You cannot use FileStream with FTP.
Instead, you need to create two FtpWebRequests (one to read and one to write).
Related
I am using below code, sometimes I face the exception
System.IO.IOException: operation did not complete successfully because the file contains a virus
string name = Request.Form["__VIEWSTATE_KEY"];
object state = null;
string fileName = string.Format("{0}\\{1}.dat", Environment.GetEnvironmentVariable("TEMP"), name );
StreamReader reader = null;
try
{
reader = new StreamReader(fileName);
state = (new LosFormatter()).Deserialize(reader);
}
catch (FileNotFoundException)
{
state = null;
}
Exception Detail:
System.IO.IOException: Operation did not complete successfully because the file contains a virus or potentially unwanted software.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize)
at System.IO.StreamReader..ctor(String path, Boolean detectEncodingFromByteOrderMarks)
at PageBase.LoadPageStateFromPersistenceMedium()
at System.Web.UI.Page.LoadAllState()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I don't think Defender is to blame. Unsafe is unsafe. Defender may have been set to guard against the use of this deserializer. Microsoft has labeled LosFormatter as unsafe in 2019, because it allows too much freedom in the type specified,
https://learn.microsoft.com/en-us/visualstudio/code-quality/ca2305?view=vs-2019
Windows Defender Advanced Threat Protection can cause .NET file operations to fail with this exception. This might not be false positive, so first scan your system, but then you can exclude your build directory.
Excluding Build directories can also speed up your build times considerably, but be aware of the risk and make sure you trust the code you're building.
I have an ASP.NET 4.5 application with a separate class library for accessing the Google analytics data. Every try to use the common methods (loading the certificat from .p12 file) ends in an "internal error" (the file will be found!) in 3rd line (Dim certificat...)
Dim scopes As String() = New String() {AnalyticsService.Scope.Analytics}
Dim serviceAccountEmail = "info#xxx.biz"
Dim certificate = New X509Certificate2(System.Web.HttpContext.Current.Server.MapPath("Certificates/MyDashboard-b335c24b1a76.p12"), "notasecret", X509KeyStorageFlags.Exportable)
Dim credential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {.Scopes = scopes}.FromCertificate(certificate))
Dim service = New AnalyticsService(New BaseClientService.Initializer() With { _
.HttpClientInitializer = credential, _
.ApplicationName = "MyDashboard" _
})
Dim MyRequest As DataResource.GaResource.GetRequest = service.Data.Ga.Get("ga:44582845", "2016-01-01", "2016-01-01", "ga:sessions")
MyRequest.MaxResults = 1000
Dim MyResult As GaData = MyRequest.Execute()
[CryptographicException: Interner Fehler.
]
System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +41
System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +307
System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +92
GoogleAnalyticsClient.Class1..ctor() in P:\Google Analytics\GoogleAnalyticsClient\Class1.vb:59
preisvergleich.Statistik.Page_Load(Object sender, EventArgs e) in \web\Webs\AFFILIATE 2.0\preisvergleich\Statistik.aspx.vb:16
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3178
Is there any possibility to access the analytics data without the certificate (I think it was in former times)?
BR Jan
I am using google as an smtp client to send an email and am having troubles with sending the attachment, i am using an asp:fileupload to choose the file then using the fileupload.filename to select the attachment. Here is the Error message.
System.IO.FileNotFoundException: Could not find file 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf'. File name: 'C:\Program Files (x86)\IIS Express\ISO Certificate.pdf' at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at System.Net.Mail.AttachmentBase.SetContentFromFile(String fileName, String mediaType) at System.Net.Mail.AttachmentBase..ctor(String fileName) at System.Net.Mail.Attachment..ctor(String fileName) at frmQuote.btnSubmit_Click(Object sender, EventArgs e) in c:\Users\jack\Documents\Visual Studio 2013\WebSites\firstarPrecision\frmQuote.aspx.cs:line 46
Then here is the C# Code to go along with it
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("EMAIL", "PASSWORD"),
EnableSsl = true
};
var msgQuote = new MailMessage
{
Subject = strQuoteSubject,
Body = strQuoteBody,
From = new MailAddress("EMAIL"),
};
//HINT HINT HERE IS WHERE THE ERROR OCCURS, I JUST DONT KNOW WHY :(
//HOW DO I TURN OFF CAPS LOCK
Attachment att = new Attachment(fupAttachment.FileName.ToString());
msgQuote.Attachments.Add(att);
msgQuote.To.Add(new MailAddress(strEmail));
client.Send(msgQuote);
}
catch (Exception ex)
{
Response.Write(ex);
}
there is the code, i obviously blocked out my credentials and such... at least i hope i got all of it.
An uploaded file needs to be saved to the server, or you could pass the file stream to the attachment (if the API supports it, not 100% sure). Either way, what you are giving it is insufficient. Save the file stream on the fupAttachment object, and then attach the file from that location. Also, depending on the version of IIS you are using determines which account accesses the file stream for permissions. The latest IIS uses an account for the apppool that needs the permissions.
System.UnauthorizedAccessException: Access to the path 'C:\Inetpub\wwwroot\HealthCard\NewsTextFiles\News.html' is denied.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
I am using ckeditor . Edit the file on server and save the file on server. It is not working on server but it is well working on my localmachine.
Here is code of edit and save button.
protected void btnSaveNews_Click(object sender, EventArgs e)
{
string str = Ckeditor.Text;
string str1 = Server.HtmlDecode(str);
//lblText.Text = str2;
FileStream fs = new FileStream(Server.MapPath("~/NewsTextFiles/News.html"), FileMode.Create , FileAccess.Write);
StreamWriter wr = new StreamWriter(fs);
wr.Write(str1);
wr.Dispose();
fs.Dispose();
pnleditor.Visible = false;
upleditor.Update();
upleditor.Visible = false;
}
Make sure the user your Application Pool is running as has write permissions on that file / folder.
This might be:
IIS_USR or Network Service (can also be others).
I want to use zedgraph in asp.net 4. but I get the erros below:
System.IO.DirectoryNotFoundException:
Could not find a part of the path C:\Users\stn-1\Desktop\ZedGraphWebAp1_CompiledSite8 \ZedGraphImages\ZedGraphWeb1fc6eb2c0-023a-4818-bff9-9c957971af4b.png. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at ZedGraph.Web.ZedGraphWeb.Render(HtmlTextWriter output)
I use the code below :
protected void ZedGraphWeb1_RenderGraph(ZedGraphWeb webObject, System.Drawing.Graphics g, MasterPane pane)
{
GraphPane myPane = pane[0];
myPane.Title.Text = "Title";
myPane.XAxis.Title.Text = "X axis label";
myPane.YAxis.Title.Text = "Y axis label";
PointPairList list1 = new PointPairList();
for (int i = 0; i < 10; i++)
{
double x = Convert.ToDouble(i);
double y = x * x;
list1.Add(x, y);
}
string textForLegend = "x-squared";
myPane.CurveList.Clear();
LineItem myCurve = myPane.AddCurve(textForLegend,
list1, Color.Red, SymbolType.Diamond);
myCurve.Symbol.IsVisible = true;
}
The reason is that zedgraph don't create a folder name "ZedGraphImages" automatically in root folder... you should create it manually...